日期:2014-05-18  浏览次数:20444 次

帮我理解下这句语句的含义
SQL code

test1
sta_id name

test2
id name

test3
id  sta_id

select test2.* from test2 where exists
(select * from test1 where exists
(select * from test3
where test1.sta_id=test3.sta_id and test2.id=test3.id))
--检索test2中的信息,where test2跟test1有关联

select test2.* from test2 where not exists
(select * from test1 where exists
(select * from test3
where test1.sta_id=test3.sta_id and test2.id=test3.id))
--检索test2中的信息,where test2跟test1没有有关联

select test2.* from test2 where not exists
(select * from test1 where not exists
(select * from test3
where test1.sta_id=test3.sta_id and test2.id=test3.id))
--这句的含义貌似是:检索跟test1所有的记录都有关联的test2中的信息
--可我理解不了,谁帮我理解下



------解决方案--------------------
IF OBJECT_ID('TEST1') IS NOT NULL
DROP TABLE TEST1;
CREATE TABLE TEST1--商品信息表
(
sta_id varchar(10),
name NVARCHAR(10)
);
INSERT INTO TEST1 VALUES
('s1','a'), 
('s2','b'),
('s3','c');
IF OBJECT_ID('TEST2') IS NOT NULL
DROP TABLE TEST2;
CREATE TABLE TEST2--客户信息表
(
id varchar(10),
name NVARCHAR(10)
);
INSERT INTO TEST2 VALUES
('i1','张三'), 
('i2','李四'),
('i3','王五');
IF OBJECT_ID('TEST3') IS NOT NULL
DROP TABLE TEST3;
CREATE TABLE TEST3--购买信息表
(
id varchar(10),
sta_id varchar(10)
);
INSERT INTO TEST3 VALUES
('i1','s1'), 
('i1','s2'),
('i1','s3'),
('i2','s1');
--查询购买过商品的客户信息
select test2.* from test2 where exists(select * from test3 where test2.id=test3.id))--查询结果
id name
i1 张三
i2 李四
--查询没有购买过商品的客户信息
select test2.* from test2 where not exists(select * from test3 where st2.id=test3.id)--查询结果
i3 王五
--查询购买过所有商品的客户信息
select test2.* from test2 where not exists
(select * from test1 where not exists
(select * from test3
where test1.sta_id=test3.sta_id and test2.id=test3.id))
--查询结果
i1 张三

--嗯,第三个查询理解不了!

第三段可以这么理解。先从TEST1,TEST2交叉连接后再找出不存在TEST3的

上面的几段可以简化