简体   繁体   中英

How can I select multiple rows with the count of other rows in the same table that has their primary keys in a separate column?

I am trying to get the parent comments from my table and the count of its child comments from the same table-

comment_id    answer_id   comment_body  parent_id
    1            51       new comment     NULL
    2            51      child comment      1
    3            51         fgdfg           1
    4            51     another comment   NULL

expected output

comment_id    answer_id   comment_body  parent_id    childs
    1            51       new comment     NULL          2
    4            51     another comment   NULL          0

I tried this query

SELECT NULL AS childs,
    tbl_answer_comment.*
FROM
    tbl_answer_comment
WHERE
    tbl_answer_comment.parent_id = NULL
UNION
SELECT
    COUNT(tbl_answer_comment.parent_id) AS childs,
    tbl_answer_comment.*
FROM
    tbl_answer_comment

But this only returns

comment_id    answer_id   comment_body  parent_id    childs
    4            51     another comment   NULL          2

I don't think you need a UNION here, you can achieve the result with a left join:

select a.*, ifnull(b.childs, 0) childs
from tbl_answer_comment a 
left join 
  (select parent_id, count(comment_id) childs 
  from tbl_answer_comment group by parent_id) b 
  on a.comment_id = b.parent_id 
where a.parent_id is null;

This Query

SELECT 
   comment_id, answer_id,  `comment_body`,c.parent_id, IFNULL(p1.childs,0) childs
FROM tbl_answer_comment  c 
LEFT Join (Select count(parent_id) childs,parent_id 
           From tbl_answer_comment  
           Where (parent_id IS NOT NULL) 
           Group by parent_id) p1
on c.comment_id = p1.parent_id 
WHERE c.parent_id IS NULL
ORDER BY c.comment_id;

gives you

comment_id  answer_id   comment_body    parent_id   childs
1           51          new comment                 2
4           51          another comment             0

I really can't see why do you want parent_id which is empty to show.

I ended up using this solution, leaving this here if someone finds it usefull-

SELECT
    j.*,
    (SELECT COUNT(*) FROM tbl_answer_comment i WHERE i.parent_id = j.comment_id) AS child_count
FROM
    tbl_answer_comment j
WHERE
    j.parent_id IS NULL

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