2011-06-17 47 views
1

我想寫一個sql查詢到以下(從這個網站http://sqlzoo.net/1b.htmCTE錯誤的語法

In which years was the Physics prize awarded but no Chemistry prize. (WARNING - this question is way too hard for this level, you will need to use sub queries or joins).

第一次嘗試:

with c as 
(select yr, subject 
from nobel 
where subject <> 'Chemistry') 

select yr 
from c 
group by yr 
having c.subject ='Physics' 

但我得到一個語法錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'with c as (select yr, subject from nobel where subject <> 'Chemistry' at line 1

有什麼不對?

第二次嘗試:

select o.yr 
from 
(select yr, subject 
from nobel 
where subject <> 'Chemistry') o 
group by o.yr 
having o.subject ='Physics' 

但我得到一個語法錯誤:

Unknown column 'o.subject' in 'having clause'

有什麼不對?

第三嘗試: 我怎麼做這與加入?

+1

你的標籤說:「TSQL」(imples的Microsoft SQL Server),但你的錯誤說:「MySQL服務器」我的猜測是這背後的網站。我猜MySQL不支持CTE。提示:EXISTS是你的朋友 – gbn 2011-06-17 09:57:19

+0

我如何改變這篇文章標籤? – 2011-06-17 09:58:37

+0

不管到CTE,其會給你同樣的問題在任何RDBMS – Ash 2011-06-17 10:07:32

回答

1

您的第一個查詢中的問題是有子句。您只能使用一個聚集在這裏

列所以這些將工作

;with c as 
(select yr, subject from nobel where subject <> 'Chemistry') 
select yr,count(c.subject) from c where c.subject ='Physics' group by yr 

;with c as 
(select yr, subject from nobel where subject <> 'Chemistry') 
select yr,count(c.subject) from c group by yr having count(c.subject) =1 

同樣的問題與第二個

Having in T- SQL

0

這是一個正確的答案,但我還是想了解我的錯誤。

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

你可以實現無子選擇了相同的結果。這是怎麼回事可以在MySQL中實現:

SELECT yr 
FROM nobel 
GROUP BY yr 
HAVING COUNT(subject = 'Chemistry' OR NULL) = 0 
    AND COUNT(subject ='Physics' OR NULL) = 1