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 に答える