通过2个连接获得比预期更高的结果

时间:2013-02-26 18:46:19

标签: mysql sql

这是我的查询:

SELECT  p.id, COUNT(c.id) AS comments, COUNT(a.id) AS answers
FROM posts_tbl AS p
LEFT JOIN post_reply_tbl AS c ON c.post_id = p.id AND c.type IN (1,3)
LEFT JOIN post_reply_tbl AS a ON a.post_id = p.id AND a.type = 2
GROUP BY p.id

我应该得到的结果是:

ID  Answers Comments
1   3       4
2   1       1
3   0       1

但相反,我得到了:

ID  Answers Comments
1   12      12
2   1       1
3   0       1

当我只使用其中一个LEFT JOIN时,无论哪一个它给我正确的答案/评论数量(取决于我使用的LEFT JOIN)。但是当我使用它们时它会给我第二个结果。

使用*时的示例结果数据:

id  username    date                subject                     year    brand   model   type    bodywork                    text                                                    image       chassis         id  post_id answer_id   username        text    date                type    id  post_id answer_id   username        text            date                type
1   Sinan Samet 2013-02-18 20:18:19 Dit is een test onderwerp   2006    Audi    A4  TFSI 2.0    TFSI 2.0 QUATTRO - 200pk    Lorem ipsum dolor sit amet consectetur adipiscing ...   test.jpg    345215453213425 5   1       NULL        Sinan Samet     Test    2013-02-26 09:19:22 1       1   1       NULL        Jan Willem      Bla             2013-02-26 14:14:17 2
1   Sinan Samet 2013-02-18 20:18:19 Dit is een test onderwerp   2006    Audi    A4  TFSI 2.0    TFSI 2.0 QUATTRO - 200pk    Lorem ipsum dolor sit amet consectetur adipiscing ...   test.jpg    345215453213425 5   1       NULL        Sinan Samet     Test    2013-02-26 09:19:22 1       2   1       NULL        Peter           Nee toch niet   2013-02-26 15:12:26 2
1   Sinan Samet 2013-02-18 20:18:19 Dit is een test onderwerp   2006    Audi    A4  TFSI 2.0    TFSI 2.0 QUATTRO - 200pk    Lorem ipsum dolor sit amet consectetur adipiscing ...   test.jpg    345215453213425 5   1       NULL        Sinan Samet     Test    2013-02-26 09:19:22 1       3   1       NULL        Homer Simpson   Doh!            2013-02-26 14:33:18 2
1   Sinan Samet 2013-02-18 20:18:19 Dit is een test onderwerp   2006    Audi    A4  TFSI 2.0    TFSI 2.0 QUATTRO - 200pk    Lorem ipsum dolor sit amet consectetur adipiscing ...   test.jpg    345215453213425 6   1       NULL        Bart Simpson    Yo      2013-02-26 08:38:37 1       1   1       NULL        Jan Willem      Bla             2013-02-26 14:14:17 2

1 个答案:

答案 0 :(得分:4)

select
    p.id,
    COALESCE(c.comments,0) AS comments,
    COALESCE(a.answers, 0) AS answers
from
    posts_tbl as p
    left join (
        select post_id, count(*) as comments
        from post_reply_tbl
        where type in (1,3)
        group by post_id
    ) as c on p.id = c.post_id
    left join (
        select post_id, count(*) as answers
        from post_reply_tbl
        where type = 2
        group by post_id
    ) as a on p.id = a.post_id
order by id ;