[英]Mysql count with GROUP_CONCAT while using join query
I have a chats table and chat_reactions table.我有一个聊天表和聊天反应表。 Each chat message can have many reactions and a reaction is a text and it can be many.每条聊天消息可以有很多反应,一个反应是一个文本,可以有很多。 I am trying to return messages with the grouped reactions and the total number of times a particular reaction is used.我正在尝试返回带有分组反应的消息以及使用特定反应的总次数。 For example,例如,
msg: hi with id 1
got a total of three reactions. msg: hi with id 1
一共得到了三个反应。 1 LIKE AND 2 LOVES
. 1 LIKE AND 2 LOVES
。 How can I return it?我该如何退货?
Here is the query I am trying这是我正在尝试的查询
SELECT c.id, c.msg, GROUP_CONCAT(cr.reaction) as reaction
FROM chats as c
LEFT JOIN chat_reactions as cr on c.id = cr.chat_id
GROUP BY c.id
My result looks like this.我的结果看起来像这样。
How can I add numbers with reaction or there are better and performant options I have?如何添加带有反应的数字,或者我有更好和性能更好的选项? Please suggest.请建议。
Thank you谢谢
First count the post reactions.首先计算后反应。 Then aggregate per post.然后汇总每个帖子。
select
c.id,
c.msg,
group_concat(concat(cr.reaction, '(', cnt, ')')
order by cr.reaction
separator ', ') as reactions
from chats as c
left join
(
select chat_id, reaction, count(*) as cnt
from chat_reactions
group by chat_id, reaction
) cr on cr.chat_id = c.id
group by c.id, c.msg
order by c.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.