使用SELECT查询分组问题

时间:2013-03-14 07:08:29

标签: mysql sql select group-by

我正在建立一个非常基础的活动管理&邀请系统。为此,我构建了2个表并使用查询列出其邀请计数为的所有事件 1.已发送的总邀请 2.接受的总数 3.拒绝总数 4.总等待

以下是查询

SELECT 
    *, 
    count(im.event_id_fk) as total_invitations, 
    count(im2.event_id_fk) as total_accepted, 
    count(im3.event_id_fk) as total_rejected,
    count(im4.event_id_fk) as total_waiting 
FROM event_mst em
LEFT JOIN invitation_mst im
    ON (em.event_id_pk = im.event_id_fk)
LEFT JOIN invitation_mst im2
    ON (em.event_id_pk = im2.event_id_fk AND im2.status = 'Accept')
LEFT JOIN invitation_mst im3
    ON (em.event_id_pk = im3.event_id_fk AND im3.status = 'Reject')
LEFT JOIN invitation_mst im4
    ON (em.event_id_pk = im4.event_id_fk AND im4.status = 'Waiting')
GROUP BY 
    im.event_id_fk, 
    im2.event_id_fk, 
    im3.event_id_fk, 
    im4.event_id_fk 
ORDER BY 
    em.date_added DESC

现在问题是此查询提供了错误的计数,例如如果共发送了3个邀请,则会给出9.如果有5个邀请已发送,则会给出25个邀请。

因此它似乎与自身相乘并返回结果。我知道这个选择查询一定有问题。有人纠正我这个问题吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

这是mysql最简单的解决方案,因为它支持布尔计算。

SELECT  event_id_pk,
        COUNT(*) as total_invitations, 
        SUM(status = 'Accept') as total_accepted, 
        SUM(status = 'Reject') as total_rejected,
        SUM(status = 'Waiting') as total_waiting 
FROM    event_mst
GROUP   BY event_id_pk

但查询不会提供有关邀请的完整详细信息,为此,您可以将查询包装在子查询中并将其与原始表本身连接,

SELECT  a.*,
        b.total_invitations,
        b.total_rejected,
        b.total_waiting
FROM    event_mst a
        INNER JOIN
        (
            SELECT  event_id_pk,
                    COUNT(*) as total_invitations, 
                    SUM(status = 'Accept') as total_accepted, 
                    SUM(status = 'Reject') as total_rejected,
                    SUM(status = 'Waiting') as total_waiting 
            FROM    event_mst
            GROUP   BY event_id_pk
        ) b ON a.event_id_pk = b.event_id_pk