2017-07-25 88 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,這是唯一一個在他的成績中沒有任何朋友的人。

第二個查詢在拉狄克的答案解釋。

我希望這會有所幫助。