c_id | c_action | r_c_id
-----------------------------
1 |发布| NULL
2 |发布| NULL
3 |发布| NULL
4 |发布| NULL
5 |回复| 1
6 |回复| 1
7 |回复| 3
8 |回复| 3
9 |回复| 3
10 |回复| 4
-----------------------------------
我希望所有“发布”结果都带有额外的列回复,其中在回复列中
将所有回复计算在c_id = r_c_id的位置,类似于bellow:
c_id | c_action | r_c_id |回复
-----------------------------------
1 |发布| NULL | 2
2 |发布| NULL | 0
3 |发布| NULL | 4
4 |发布| NULL | 1
答案 0 :(得分:1)
这是一个简单的SELF JOIN到同一个表,条件是连接c_id和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