0

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. 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.

[![enter image description here][1]][1]

How can I add numbers with reaction or there are better and performant options I have? Please suggest.

Thank you

4
  • 1
    I would look up conditional aggregation. Assuming you have a small number of reaction types, this should be a good solution. Commented Sep 8, 2022 at 18:03
  • Could you add an example please Commented Sep 8, 2022 at 18:04
  • Do you need the output in one column (1 like 2 loves) or rather as individual columns. The conditional aggregation works great for individual columns. Commented Sep 8, 2022 at 18:11
  • Individual one if you could show Commented Sep 8, 2022 at 18:13

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

6 Comments

Getting error In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'db.c.id'; this is incompatible with sql_mode=only_full_group_by
@HkmSadek -- see the up date -- the out select needed the group by statement.
Thanks it works. What do you think about this approach? Is there any really better ways to do unlimited types of reactions support?
@Hogan: Thank you. I had group by c.id and then removed it by mistake. (The group by on the id alone should suffice as the msg is functionally dependent on the primary key column.)
Unlimited? If the messages string gets too long, it will be truncated. You can alter the length limit, however. See dev.mysql.com/doc/refman/8.0/en/….
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.