2010-04-23 39 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