2013-08-23 41 views
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 

回答

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

+0

我忘了給帖子添加一些東西。我需要用一個數字來劃分commentScount,比如0.5。我怎麼做? –

+0

根據您的要求更新 – shola

+0

非常感謝:) –

相關問題