[英]Query within another query to count amount of items from another table
這是一個匯總的數據庫架構:
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
嘗試這個:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.