这是我的查询:
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
当我只使用 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