2010-02-24 80 views
2

如果我有這樣的一個表:子查詢的MySQL

yr   subject 
1960 Physics 
1960 Chemistry 
1961 Physics 
1962 Chemistry 

我希望所有這些年來當主題是物理學,而不是化學

如果我試試這個,它並沒有給我正確的結果。

select yr from table where subject = "Physics" and 
yr NOT IN (select yr from table where subject = "Chemistry") 
+0

出於好奇,這是什麼回報? – Craig 2010-02-24 16:25:48

+0

它返回一個額外的年份行 – JPro 2010-02-24 16:32:04

回答

0

您的查詢的問題在於,您在返回兩次物理獎項時返回了兩次。添加DISTINCT關鍵詞給你剛剛年(根據question 3A on this site

SELECT DISTINCT yr FROM nobel 
WHERE 
    subject = 'Physics' AND 
    yr NOT IN (SELECT yr FROM nobel WHERE subject = 'Chemistry'); 
+0

嗨,謝謝你試圖幫助我。我試圖在'http:// sqlzoo.net/1b.htm'這裏解決問題3a。查詢仍然給我錯誤。 – JPro 2010-02-24 16:36:52

+0

對不起,我使用'tableName'而不是'nobel'的實際表名:) – Amadiere 2010-02-24 18:08:22

0

試試這個:

select yr from table t1 where subject = 'Physics' 
where not exists 
(select yr from table t2 where subject = 'Chemistry' and t1.yr = t2.yr) 
+0

它給我sql語法錯誤 – JPro 2010-02-24 16:32:35

+0

輕微的錯字末尾......應該讀取t1.yr = t2.yr – Dancrumb 2010-02-24 16:33:11

+0

謝謝爲了指出這一點。固定。 – 2010-02-24 16:34:40

0

這其中解決了您的鏈接指出了一個問題:

SELECT DISTINCT n1.yr 
FROM nobel n1 
WHERE n1.subject = 'Physics' 
AND n1.yr NOT IN (
    SELECT DISTINCT n2.yr 
    FROM nobel n2 
    WHERE n2.subject = 'Chemistry' 
) 

原因這一個作品是因爲它消除了重複的年份。由於價格可以由同一年和多個主題的多個人授予,因此您希望刪除重複項。您也可以跳過內部查詢的DISTINCT,這會跳過一個排序步驟。在生產中,您需要分析此查詢並創建適當的索引。

+0

感謝您的更新。我應該在查詢中顯示這個主題,以便我能夠抓到兩個物理獎項。無論如何,謝謝。 – JPro 2010-02-24 16:49:20

+0

只是出於好奇,是否有人用示例數據問SQL問題,你真的會創建表並回答問題,還是隻通過查看數據給出答案? – JPro 2010-02-24 16:50:16

+0

你的分析意味着什麼? – JPro 2010-02-24 16:51:44

1

在sqlzoo的問題是有點棘手,因爲沒有爲1933年等十餘一個物理學獎,正確的答案是:

select distinct yr from nobel as n1 
where subject = 'Physics' 
and not exists 
    (select 1 from nobel as n2 where n2.subject = 'Chemistry' and n2.yr = n1.yr) 

你可以利用這個查詢檢查結果1933年有:

select * from nobel where yr = 1933 
+0

只是出於好奇,是否有人用示例數據問SQL問題,你真的會創建表並回答問題,還是隻通過查看數據給出答案? – JPro 2010-02-24 16:50:37

+0

取決於查詢的複雜程度。 :-) – 2010-02-24 16:57:16

0

你幾乎沒有......你需要使用不同的:

select distinct yr from table where subject = "Physics" and 
yr NOT IN (select yr from table where subject = "Chemistry") 

對於鏈接給出:

select distinct yr from nobel 
where subject = 'Physics' and 
yr not in (select yr from nobel where subject = 'Chemistry')