sql exist的妙用
作者:sw47 来源:sw47的blog 时间:2007-11-08 11:47:00
sql exist的妙用
create table b(a varchar(10),b varchar(10),c varchar(10))
insert into b (a,b,c) values ('aaa','bbb','ccc')
insert into b (a,b,c) values ('aaa','bbb','ccc')
insert into b (a,b,c) values ('aaa1','bbb1','ccc1')
insert into b (a,b,c) values ('aaa2','bbb2','ccc2')
insert into b (a,b,c) values ('aaa2','bbb3','ccc4')
create table a(a varchar(10),b varchar(10),c varchar(10))
insert into a (a,b,c) values ('aaa','bbb','ccc')
insert into a (a,b,c) values ('aaa','bbb','ccc')
insert into a (a,b,c) values ('aaa1','bbb1','ccc1')
insert into a (a,b,c) values ('aaa2','bbb2','ccc2')
insert into a (a,b,c) values ('aaa2','bbb3','ccc4')
select * from a inner join b on a.a=b.a and a.b=b.b and a.c=b.c
select * from a where exists(select * from b where a=a.a and b=a.b and c=a.c)
select x,y,z from (select a.a as x,a.b as y,a.c as z from a, b where a.a=b.a and a.b=b.b and a.c=b.c) as a group by x,y,z
在有id的情况下in和exist差不多,但是没有id的话exist用处就大了
USE pubs
GO
SELECT DISTINCT pub_name
FROM publishers
WHERE EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers.pub_id
AND type = 'business')
GO
-- Or, using the IN clause:
USE pubs
GO
SELECT distinct pub_name
FROM publishers
WHERE pub_id IN
(SELECT pub_id
FROM titles
WHERE type = 'business')
GO