-3

I have a table named "comment", like bellow :

c_id | c_action | r_c_id
-----------------------------
1 | post | NULL
2 | post | NULL
3 | post | NULL
4 | post | NULL
5 | reply | 1
6 | reply | 1
7 | reply | 3
8 | reply | 3
9 | reply | 3
10 | reply | 4

-----------------------------------

I want to all 'post' result with a extra column replies, where in replies column
count all reply where c_id = r_c_id, something like bellow:

c_id | c_action | r_c_id | replies
-----------------------------------
1 | post | NULL | 2
2 | post | NULL | 0
3 | post | NULL | 4
4 | post | NULL | 1


1 Answers1

1

This is a simple SELF JOIN to the same table with condition connecting c_id with rep_c_id:

SELECT
  t1.c_id, 
  t1.c_action,
  t1.rep_c_id,
  COUNT(t2.c_id) AS replies
FROM
  tablename t1
  LEFT JOIN tablename t2 ON t1.c_id = t2.rep_c_id
WHERE
  t1.c_action = 'post'
GROUP BY t1.c_id, t1.c_action, t1.rep_c_id
Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72