睡觉前最后一问:求一个多表查询SQL语句!
表A
字段:
UID PID
1 1
1 2
2 1
3 2
表B
字段:
PID Des
1 'admin '
2 'super '
怎么实现取得UID=1的记录,即:Des既等于 'admin ',又等于 'super '的记录。
我知道用where exists (...where Des=) and exists (...where Des=)可以实现。
可是感觉效率不是很高的。怕数据量大了,速度慢。
那位大哥能给个优化的查询语句啊?谢谢~
(明天结帖)
------解决方案--------------------declare @ta table(UID int,PID int)
insert @ta
select 1, 1 union all
select 1, 2 union all
select 2, 1 union all
select 3, 2
declare @tb table(PID int,Des varchar(20))
insert @tb
select 1, 'admin ' union all
select 2, 'super '
SELECT UID FROM (select UID from @ta group by UID,PID) as t
group by UID having count(*)=(select count(*) from @tb)
/*
UID
-----------
1
*/
------解决方案--------------------select distinct uid from @ta a where
not exists
(select * from @tb where pid
not in (select pid from @ta b where a.uid=b.uid ))