简体   繁体   中英

Query within another query to count amount of items from another table

Here's a summarized database schema:

Table: posts 
Columns: id, contents

Table: comments
Columns: id, post_id, contents

Here's what I want to do:

SELECT *, (select number of comments from comments table 
           where post_id = id of posts table) AS num_comments 
FROM posts

Try this:

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;

See this SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM