事件主持人 – 包含三位常规主持人和一个“其他”字段(如果有人替换他们)或编辑:作为嘉宾主持人(除了常规主持人之外) )
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
或者:
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
有人可以告诉我如何实现这一目标或为我指明方向吗?
最佳答案
使用这个:
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
关于mysql - 计算并连接两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2698464/