2012-09-17 112 views
1

我查詢的目標是返回國家,大寫和所用語言的數量。它還需要按照語言數量的降序排列,然後由大寫字母排序。最後,語言的數量必須至少爲5和10或更少。SQL查詢無法正常工作,返回任何內容

這裏是我的查詢:

SELECT country.name     AS Country, 
     city.name      AS Capital, 
     Count(countrylanguage.language) AS NumLanguages 
FROM country, 
     city, 
     countrylanguage 
WHERE city.id = country.capital 
GROUP BY city.name, 
      country.name 
HAVING (Count(countrylanguage.language) BETWEEN 5 AND 10); 

它沒有返回。 where子句是必需的,才能顯示城市名稱。在國家表中只是一個身份證號碼,然後城市名單中包含身份證號碼和姓名。

如果任何人都可以發現我的錯誤我「將非常感謝!

+0

這是功課?這很好,如果是這樣,最好提一下。 –

回答

4

你缺少與countrylanguage的關係。沒有它,你有一個笛卡爾積,因此Count(countrylanguage.language)等於記錄在countrylanguage的數量,這是最有可能是大於10

這裏有一個建議的解決方案(調整字段名/ DB結構相應地):

SELECT country.name     AS Country, 
     city.name      AS Capital, 
     Count(countrylanguage.language) AS NumLanguages 
FROM country, 
     city, 
     countrylanguage 
WHERE city.id = country.capital 
AND countrylanguage.language_id = country.language_id 
GROUP BY city.name, 
      country.name 
HAVING (Count(countrylanguage.language) BETWEEN 5 AND 10) 
ORDER BY NumLanguages desc, city.Name 

這就是說,你應該在儘量避免在查詢的WHERE子句中加入連接(隱式連接)。使用顯式(聲明式)連接會給你更多的可讀性和更多的靈活性。

更新

按照意見建議,這裏是一個使用ANSI-92連接語法查詢的版本:

SELECT country.name     AS Country, 
     city.name      AS Capital, 
     Count(countrylanguage.language) AS NumLanguages 
FROM  country 
INNER JOIN city on city.id = country.capital 
INNER JOIN countrylanguage on countrylanguage.language_id = country.language_id 
GROUP BY city.name, 
      country.name 
HAVING (Count(countrylanguage.language) BETWEEN 5 AND 10); 
ORDER BY NumLanguages desc, city.Name 
+1

如果有效,我印象深刻。正如OP所說,笛卡爾產品會返回太多的行,而不是任何行。 – ahillman3

+1

@ ahillman3閱讀我更新的答案。 OP希望團體'HAVING(Count(countrylanguage.language)between 5 and 10)',所以**許多**最有可能超過10 –

+1

@ ahillman3 - 我同意這可能是解釋。沒有ANSI-92連接語法?如果OP首先使用它,他們不會有這個問題... –