我有 2 张桌子,EVENT
并且EVENT_INVITATION
. 我想选择所有事件:
EVENT.creator_id = x
OR
EVENT_INVITATION.invitee_id = x
但我还需要返回EVENT_INVITATION
每个结果的总行数EVENT
。
我认为这会做到:
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原因,我无法测试它。
获取您关心的所有事件的列表,然后计算相关的邀请。在没有邀请的情况下外部加入。
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