在另一个查询中查询以计算另一个表中的项目数量

时间:2013-08-23 06:19:44

标签: mysql sql subquery

这是一个汇总的数据库架构:

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

1 个答案:

答案 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;

请参阅this SQLFiddle