计算并连接两个表

时间:2010-04-23 12:33:08

标签: mysql join count

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

有人可以告诉我如何实现这一目标或指出我的方向吗?

3 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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