2013-02-22 62 views
0

我知道這與此問題類似:MySQL Query - Sum one related table - Count another related table但我無法讓它適用於我。MySQL - 在一個表中計數記錄並在另一個表中計數記錄

我有3個表:

  • Event
  • Attendee
  • Gifts

對於每一個我們需要總結的Attendees的數量和Gifts總量EventAttendee可能會或可能不會收到禮物。

我可以得到它的工作,所以,如果我忽略了禮物總計,我得到這個查詢正確答案:

SELECT event.name AS name, count(*) AS num_attendee 
FROM attendee 
RIGHT JOIN event on event.id = attendee.event_id 
WHERE event.company_id =6 
GROUP BY event.id 

但我不知道如何總結(即Gift.Amount值)給出的禮物給所有Attendees爲每個事件。當我嘗試簡單加入Gift表時,根據event_id所有數字都變得古怪。

+0

你有一些樣本輸入和輸出? – 2013-02-22 00:19:13

+0

您可能正在獲得[笛卡爾產品](http://en.wikipedia.org/wiki/Cartesian_product),因爲參與者和禮物每個event_id都有多個記錄。如果是這種情況,請在使用[派生表](http://www.sqlteam.com/article/using-derived-tables-to-calculate-aggregate-values)之前先對子表執行聚合加入到父表中。 – 2013-02-22 00:46:56

回答

0

這是O'K在MS-SQL 2000:

SELECT event.name AS name, count(*) num_attendee ,amount 
FROM attendee 
RIGHT JOIN event on event.id = attendee.event_id 
LEFT OUTER JOIN(
    SELECT event_id,amount=SUM(Amount) 
    FROM Gifts 
    GROUP BY event_id 
) Gifts ON Gifts.event_id=event.id 
WHERE event.company_id =6 
GROUP BY event.name,amount 
+0

工作很好 - 非常感謝!男人,我爲此奮鬥了一段時間! – 2013-02-22 01:03:58

0

你是否正確地連接了連接?你應該有兩個在禮品表中的事件和參與者:

from attendee right join 
    event 
    on event.id = attendee.event_id right join 
    gifts 
    on event.id = gifts.event_id and attendee.id = gifts.attendee_id 
相關問題