====求个sql语句====
表1:用户表user_table
列名:id,user_name
表2:用户关系表user_relation_table
列名:id,user1_id,user2_id,state;
其中user_table.id 对应user_relation_table.user1_id 和user2_id
现在有个需求:
知道两个user_name,要找出他们之前的关系(user_relation_table.state)
我现在能想到的是,首先,根据
select id from user_table where user_name = ?
去拿到两个user_id
再用两个user_id去拿state
select state from user_relation_table where user1_id=? and user2_id = ?
请问高手们,如何优化这个语句?(写成一句?)
[解决办法]
create table user_table(id int,[user_name] nvarchar(10))
insert into user_table values (1,'爷爷')
insert into user_table values (2,'爸爸')
insert into user_table values (3,'儿子')
create table user_relation_table(id int, user1_id int,user2_id int,[state] nvarchar(10))
insert into user_relation_table values(1,1,2,'父-子')
insert into user_relation_table values(2,1,3,'爷-孙')
insert into user_relation_table values(3,2,3,'父-子')
select urt.state
from user_relation_table urt
LEFT JOIN user_table ut1
on urt.user1_id=ut1.id
INNER JOIN user_table ut2
on urt.user2_id=ut2.id
where ut1.[user_name]='爷爷' and ut2.[user_name]='儿子'
/*
state
爷-孙
*/