2017-07-25 170 views
1

我似乎无法理解为什么这两个查询以下任务返回不同的结果:“发现学生谁只有有朋友在同档次的名称和等级回到依等级排序的结果,然后在每个年级的名字。“差异查询

表在这里:https://lagunita.stanford.edu/c4x/DB/SQL/asset/socialdata.html

第一个查询:

SELECT DISTINCT h1.name, h1.grade 
FROM Highschooler h1, Friend f, Highschooler h2 
WHERE h1.ID = f.ID1 AND h2.ID = f.ID2 AND h1.grade = h2.grade 
ORDER BY h1.grade, h1.name 

第二个查询:

select name, grade from Highschooler 
where ID not in (
    select ID1 from Highschooler H1, Friend, Highschooler H2 
    where H1.ID = Friend.ID1 and Friend.ID2 = H2.ID and H1.grade <> H2.grade) 
order by grade, name; 

第二个返回预期的结果,但不是第一个。如果有人关心澄清,谢谢。

+0

,你可以在“但不是第一个”更精确?它以何种方式出乎意料? (如果您可以显示结果或相关部分,效果会更好) – Kaddath

+0

更有意义的是两个查询都不会回答问题。 –

回答

1

的第一个查询同时适用于查询三个滤的所有数据表和返回只是那些符合所有筛选条目。第二个查询首先做一个子查询它返回匹配子查询条件的行,然后这是不是有返回,其中也包括对于H1.ID = Friend.ID1Friend.ID2 = H2.ID不持有真实ID的所有ID。你可以尝试这样的:

select name, grade from Highschooler 
where where H1.ID = Friend.ID1 and Friend.ID2 = H2.ID and ID not in (
    select ID1 from Highschooler H1, Friend, Highschooler H2 
    where H1.ID = Friend.ID1 and Friend.ID2 = H2.ID and H1.grade <> H2.grade) 
order by grade, name; 
1

它可以是标准的NULL相关的行为。演示

create table tble (ID int, col int); 
insert tble(ID, col) 
values (1,1),(2,null),(3,2); 

select * 
from tble 
where col=1; 

select * 
from tble 
where ID not in (select t2.ID from tble t2 where t2.col<>1); 

因为select t2.ID from tble t2 where t2.col<>1不能返回ID 2作谓语NULL <> 1不计算结果为TRUE。

1

我只是想在第一个查询说明添加进一步澄清。第一个查询结果是:

SELECT DISTINCT h1.name, h1.grade FROM Highschooler h1, Friend f, Highschooler h2 WHERE h1.ID = f.ID1 AND h2.ID = f.ID2 AND h1.grade = h2.grade ORDER BY h1.grade, h1.name; 
    +-----------+-------+ 
    | name  | grade | 
    +-----------+-------+ 
    | Cassandra |  9 | 
    | Gabriel |  9 | 
    | Jordan |  9 | 
    | Tiffany |  9 | 
    | Andrew | 10 | 
    | Brittany | 10 | 
    | Haley  | 10 | 
    | Kris  | 10 | 
    | Alexis | 11 | 
    | Gabriel | 11 | 
    | Jessica | 11 | 
    | John  | 12 | 
    | Jordan | 12 | 
    | Kyle  | 12 | 
    | Logan  | 12 | 
    +-----------+-------+ 
    15 rows in set (0,00 sec) 

既然你执行的是笛卡尔乘积(通过选择同一台Highschooler两次的方式),以及你的条件之一h1.grade = h2.grade,你要检索具有所有学生至少有一位同级的朋友。你唯一没有得到的学生是Austin,这是唯一一个在他的成绩中没有任何朋友的人。

第二个查询在拉狄克的答案解释。

我希望这会有所帮助。