2010-04-23 91 views
0

Eventhosts - 包含三個常規主機和「其他」字段(如果有人代替)或編輯:作爲一個嘉賓主持(除了常客)計數和連接兩個表

eventid | host (SET[Steve,Tim,Brian,other]) 
------------------------------------------- 
     1 | Steve 
     2 | Tim 
     3 | Brian 
     4 | Brian 
     5 | other 
     6 | other 

事件

id | other | name etc. 
---------------------- 
1 |  | … 
2 |  | … 
3 |  | … 
4 | Billy | … 
5 | Billy | … 
6 | Irwin | … 

這個查詢:

SELECT h.host, COUNT(*) AS hostcount 
FROM host AS h 
LEFT OUTER JOIN event AS e ON h.eventid = e.id 
GROUP BY h.host 

返回:

Steve | 1 
Tim | 1 
Brian | 2 
other | 2 

我想它返回:

Steve | 1 
Tim | 1 
Brian | 2 
Billy | 1 
Irwin | 1 

OR:

Steve |  | 1 
Tim |  | 1 
Brian |  | 2 
other | Billy | 1 
other | Irwin | 1 

而且

Steve |  | 1 
Tim |  | 1 
Brian |  | 1 
Brian | Billy | 1 
other | Billy | 1 
other | Irwin | 1 

有人可以告訴我如何實現這個目標或指向一個方向嗎?

回答

1

使用此:

SELECT IF(h.host != 'other', h.host, e.other) as the_host, COUNT(e.*) AS hostcount 
FROM host h 
LEFT JOIN event e ON h.eventid = e.id 
GROUP BY the_host 

只是注意,不要使用COUNT(*),如果主機不具備時,它會顯示1而不是0。使用COUNT(e.*)

對於最後的結果,使用此:

SELECT h.host, e.other, COUNT(e.*) AS hostcount 
FROM host h 
LEFT JOIN event e ON h.eventid = e.id 
GROUP BY IF(h.host != 'other', h.host, e.other), 
    h.host, e.other -- try repeating it here 

[編輯]

試過以下查詢(即沒有建議重複GROUP BY上的字段),它也適用於您的原始問題和您編輯的問題。我現在剛剛安裝了MySQL,我不知道它是否對數據庫類型有影響,我只啓用了InnoDB和嚴格的設置。順便說COUNT(e.*)(這是ANSI SQL-接受我相信)不會對MySQL的工作,而不是必須使用COUNT(e.id)(也許你已經在你的查詢修改):

SELECT h.host, e.other, COUNT(e.id) AS hostcount 
FROM host h 
LEFT JOIN event e ON h.eventid = e.id 
GROUP BY IF(h.host != 'other', h.host, e.other) 
    -- note: i removed the suggested repeating of fields here, it works on my box here.  
    -- Settings: InnoDB and strict mode 
+0

謝謝,但這隻會返回前「其他」主機,而不是第二個。 – Eikern 2010-04-23 13:14:56

+0

嗯..它不會返回歐文?有趣。我的查詢的輸出是什麼? – 2010-04-23 13:18:45

+0

那麼我的例子是我的數據庫的簡化版本,它非常相似。並翻譯它返回:史蒂夫,11; Tim,11歲; Brian,5歲;比利,2。(比利應該有1和歐文之一。) – Eikern 2010-04-23 13:22:31

1

只需刪除GROUP BY(因爲您不希望它爲該列摺疊值),並將event.other列添加到列列表中。

SELECT h.host, e.other, COUNT(*) AS hostcount 
    FROM host AS h 
    LEFT OUTER JOIN event AS e ON h.eventid = e.id 

我只記得你可以實現第一個解決方案,並通過:

SELECT IF(h.host = 'other', e.other, h.host) AS host, COUNT(*) AS hostcount 
    FROM host AS h 
    LEFT OUTER JOIN event AS e ON h.eventid = e.id 
1
SELECT eh.host, e.other, count(*) 
FROM Eventhosts eh 
LEFT JOIN Event e ON (eh.eventid = e.id) 
GROUP BY eh.host, e.other 

回報

Steve |  | 1 
Tim |  | 1 
Brian |  | 1 
other | Billy | 1 
other | Irwin | 1