2个查询的结果竟然一样
有2个关系:
Product (pname, price, cid)
Company(cid, cname, city)
插入元祖:
insert into Product values ('gizmo', 100, 1);
insert into Product values('powergizmo', 200, 1);
insert into Product values('iStuff', 500, 2);
insert into Product values('gadget', 300, 2);
insert into Product values('powergadget', 400, 2);
insert into Company values(1,'GizmoWorks','San Jose');
insert into Company values(2,'BigCompany','Boston');
insert into Company values(3,'PowerWorks','Seattle');
运行查询:
select distinct x.city,(select count(*)
from product y
where x.cid = y.cid)
from company x
select distinct x.city,(select count(*)
from product y, company z
where z.cid = y.cid and z.city = x.city)
from company x
drop table Product,Company
create table Product(pname varchar(100), price int, cid int)
create table Company(cid int,cname varchar(100),city varchar(100))
insert into Product values ('gizmo', 100, 1);
insert into Product values('powergizmo', 200, 1);
insert into Product values('iStuff', 500, 2);
insert into Product values('gadget', 300, 3); --修改cid为3
insert into Product values('powergadget', 400, 4); --修改cid为4
insert into Company values(1,'GizmoWorks','San Jose');
insert into Company values(2,'BigCompany','Boston');
insert into Company values(3,'PowerWorks','Seattle');
insert into Company values(4,'PowerWorks','Seattle'); --增加一条
select distinct x.city,(select count(*)
from product y
where x.cid = y.cid)
from company x
/*
city (无列名)
Boston 1
San Jose 2
Seattle 1
*/
select distinct x.city,(select count(*)
from product y, company z
where z.cid = y.cid and z.city = x.city)
from company x
/*
city (无列名)
Boston 1
San Jose2
Seattle 2
*/
Msg 512, Level 16, State 1, Line 16如果cid已经足够唯一标识,就可以不用city,否则就需要加上去
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.