0

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

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
4

1 回答 1

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;

看到这个 SQLFiddle

于 2013-08-23T06:23:49.807 回答