MySQL与Count连接查询

时间:2012-09-19 22:14:31

标签: mysql sql

我有2个表,EVENTEVENT_INVITATION。我想选择所有事件:

EVENT.creator_id = x
OR
EVENT_INVITATION.invitee_id = x

但我还需要为每个结果EVENT_INVITATION返回EVENT行的总数。

2 个答案:

答案 0 :(得分:1)

我认为这样做会:

SELECT count(*), EVENT.event_id
FROM EVENT, 
EVENT_INVITATION, 
(
  SELECT event_ID
  FROM EVENT
  WHERE creator_id = x
  UNION
  SELECT event_id
  FROM EVENT_INVITATION.
  WHERE invitee_id = x) temp
WHERE EVENT.event_ID = EVENT_INVITATION.event_ID
AND EVENT.event_ID = temp.event_ID
GROUP BY EVENT.event_id

我建议在没有数据结构和样本集的情况下执行sql fiddle原因我无法对其进行测试。

答案 1 :(得分:0)

获取您关注的所有事件的列表,然后计算相关的邀请。外部联接,以防没有邀请。

WITH selectEvents AS (
    SELECT event_id
      FROM event
      WHERE creator_id = <x>
    UNION
    SELECT event_id
      FROM event_invitation
      WHERE invitee_id = <x>
)
SELECT s.event_id, COUNT(i.event_id) AS theCount
  FROM selectEvents s
  LEFT OUTER JOIN event_invitation i ON (i.event_id = s.event_id)
  GROUP BY s.event_id