2011-06-30 158 views
1

表1:食品新到SQL - 需要幫助的查詢

id name 
------- 
1 Hot-dog 
2 Sandwich 
3 Apple 

表2:報告

id food_id date 
---------------- 
1  1 2010-01-01 
2  1 2010-02-01 
3  2 2011-02-01 

我怎樣才能設計出一個查詢到食品表選擇的所有食物一個名爲numReports的變量,它是食品在報告中所有報告的總數量。

我一直想:

SELECT 
    food.id AS foodId, 
    food.name AS foodName, 
    count(
     SELECT * FROM reports WHERE reports.food_id=food.id 
     ) AS numReports 
FROM 
    food 

輸出:

id name numReports 
------------------- 
1 Hot-dog 2 
2 Sandwich 1 
3 Apple 0 
+0

差不多吧,只是移動'Count'子選擇內。 – Magnus

+0

提到你的答案尋求幫助,謝謝。爲什麼人們會選擇使用INNER JOIN而不是我們所做的方式? – Chris

+0

我不知道,它更容易與子查詢編寫(因爲我們有),因爲你不必指定列的所有組(可以很多),如果你沒有在主鍵上分組子查詢將會有更好的表現。 – Magnus

回答

0
SELECT 
    food.id AS foodId, 
    food.name AS foodName, 
    (SELECT COUNT(*) FROM reports WHERE reports.food_id = food.id) 
FROM 
    food 
3
SELECT food.name, 
     COUNT(*) as food_count 
    FROM reports 
     INNER JOIN food ON reports.food_id = food.id 
    GROUP BY food.name; 
2

您可以通過使用GROUP BY實現這一目標。

SELECT  food.id AS foodId, 
      food.name As foodName, 
      Count(*) AS numReports 
FROM  food 
INNER JOIN reports 
ON   food.id = reports.food_id 
GROUP BY food.id, 
      food.name 

你也可以使用相關的子查詢。

SELECT  food.id AS foodId, 
      food.name As foodName, 
      (SELECT Count(*) FROM reports WHERE food.id = reports.food_id) AS numReports 
FROM  food  
+0

這就是我正在尋找的優化...新的groupby是正確的樹;) –

0

有可能是一種優化的方式來做到這一點,但這裏有一個查詢,應該讓您的結果

select 
    food.id, 
    food.name, 
    reports.reportcount 
from 
    food 
inner join 
    (select 
    food_id, 
    count(food_id) reportcount 
    from 
     report 
    group by (food_id)) as reports 
on food.id=reports.food_id