这是一个汇总的数据库架构:
Table: posts
Columns: id, contents
Table: comments
Columns: id, post_id, contents
这就是我想要做的事情:
SELECT *, (select number of comments from comments table
where post_id = id of posts table) AS num_comments
FROM posts
答案 0 :(得分:1)
试试这个:
SELECT p.*
,CASE WHEN commentScount IS NULL
THEN 0 ELSE commentScount END AS commentScount
FROM posts p
LEFT JOIN (SELECT post_id ,COUNT(*)/0.5 commentScount
FROM comments GROUP BY post_id) AS c
ON p.id = c.post_id;