我需要一个包含posts-id,posts-title,posts-created_at,users-name,number-of-comments和likes-status的查询。如果不存在,则likes-status为0。像这样:
id |title |created_at |name |status |commentscount |
========================================================
1 |Hello 1 |2015-07-22 |Baker |-2 |2 |
2 |Hallo 2 |2015-07-23 |Tom |0 |0 |
我的尝试:
SELECT p.id, p.title, p.created_at, u.name, COALESCE(c.body, 0) as commentscount, COALESCE(sum(l.status), 0) as status
FROM posts p
LEFT OUTER JOIN likes l ON l.post_id = p.id
LEFT OUTER JOIN users u ON u.id = p.user_id
LEFT OUTER JOIN comments c ON c.post_id = p.id
GROUP BY p.id, p.title, p.created_at, u.name, c.body
结果:应该汇总id 1,并且commentscount应该是2.状态-2应该保留。
id |title |created_at |name |status |commentscount |
========================================================
1 |Hello 1 |2015-07-22 |Baker |-2 |Comment 1 | << issue
1 |Hello 1 |2015-07-22 |Baker |-2 |Comment 2 | << issue
2 |Hallo 2 |2015-07-23 |Tom |0 |0
用户表
id |name |email |password |created_at |
====================================================
1 |Baker |baker@example.com |UHds(& |2015-07-20 |
2 |Tom |tom@example.com |ihj=)? |2015-07-21 |
帖子表
id |user_id |title |created_at |
==================================
1 |1 |Hello 1 |2015-07-22 |
2 |2 |Hello 2 |2015-07-23 |
喜欢桌子
id |user_id |post_id |status |created_at |
===========================================
1 |1 |1 |-1 |2015-07-24 |
2 |2 |1 |-1 |2015-07-25 |
评论表
id |user_id |post_id |body |created_at |
==============================================
1 |1 |1 |Comment 1 |2015-07-28 |
2 |2 |1 |Comment 2 |2015-07-28 |
答案 0 :(得分:1)
SELECT
COUNT(p.id), p.title, p.created_at, u.name, COUNT(c.body) as commentscount,
IFNULL(sum(l.status),0) as status
FROM posts p
LEFT JOIN likes l ON l.post_id = p.id
LEFT JOIN users u ON u.id = p.user_id
LEFT JOIN comments c ON c.post_id = p.id
GROUP BY p.title
答案 1 :(得分:1)
您可以只使用所需的计数加入子查询。这将加快您的查询速度并消除外部子句中GROUP BY
的需要:
SELECT p.id, p.title, p.created_at, u.name, COALESCE(c.comments_count, 0) AS comments_count, COALESCE(l.status_sum, 0) AS status_sum
FROM posts p
LEFT OUTER JOIN users u ON u.id = p.user_id
LEFT OUTER JOIN (
SELECT l.post_id, SUM(l.status) AS status_sum
FROM likes l
GROUP BY l.post_id
) l ON l.post_id = p.id
LEFT OUTER JOIN (
SELECT c.post_id, COUNT(*) as comments_count
FROM comments c
GROUP BY c.post_id
) c ON c.post_id = p.id