[英]Mysql count with GROUP_CONCAT while using join query
我有一個聊天表和聊天反應表。 每條聊天消息可以有很多反應,一個反應是一個文本,可以有很多。 我正在嘗試返回帶有分組反應的消息以及使用特定反應的總次數。 例如,
msg: hi with id 1
一共得到了三個反應。 1 LIKE AND 2 LOVES
。 我該如何退貨?
這是我正在嘗試的查詢
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
我的結果看起來像這樣。
如何添加帶有反應的數字,或者我有更好和性能更好的選項? 請建議。
謝謝
首先計算后反應。 然后匯總每個帖子。
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.