我正在尝试将Xoops帖子转换为Wordpress。作为其中的一部分,我想得到一个主题的评论计数。帖子和回复都在同一个“topic_id”上。如何计算它们并将其发布到新列?
数据库当前状态
topic_id | subject |comment_count|
+________+_____________________+_____________+
1 | welcome |
1 | Re: welcome |
2 | hello world |
2 | Re: hello world |
2 | Re: hello world |
3 | hello friends |
从这里我想把(topic_id - 1的数量)作为重放次数(评论次数)。指导我在MYSQL中查询
我想将输出放在同一个表中。 (COMMENT_COUNT)
数据库预期输出
| topic_id | subject |comment_count|
+________+_____________________+_____________+
| 1 | welcome | 1
| 1 | Re: welcome | 1
| 2 | hello world | 2
| 2 | Re: hello world | 2
| 2 | Re: hello world | 2
| 3 | hello friends | 0
答案 0 :(得分:1)
select *,t2.comment_count from table t1
join
(
select count(*),CONCAT('Re', ' ', subject)
as replay,topic_id as comment_count
from table
where suject=replay group by topic_id
) as t2 on t1.topic_id=t2.topic_id
答案 1 :(得分:0)
SELECT
xoops.topic_id, topic, xoops2.commentCount
FROM
xoops JOIN
(
SELECT
xoops.topic_id,
commentCount = COUNT(1) - 1
FROM
xoops
GROUP BY
xoops.topic_id
) AS xoops2 ON xoops.topic_ID = xoops2.topic_ID