search

Home  >  Q&A  >  body text

How to group and count in MySQL?

I'm trying to write a query that extracts the total number of undeleted messages sent to friends. Here is a screenshot of the table structure:

The output I want to achieve is as follows:

id          messages_count
 ---------------------------
 1            4562
 2            7255

Here are the queries I have tried so far:

SELECT u.id, count( CASE WHEN m.is_deleted = false THEN m.is_deleted END ) as messages_count
FROM users u
inner join messages m on u.id = m.to_id
GROUP BY u.id
ORDER BY u.id;

P粉478835592P粉478835592260 days ago618

reply all(1)I'll reply

  • P粉662802882

    P粉6628028822024-04-07 11:24:38

    Have you tried anything similar?

    SELECT u.id, count( m ) as messages_count
    FROM users u
    inner join messages m on u.id = m.to_id and m.is_deleted = false
    GROUP BY u.id
    ORDER BY u.id;

    reply
    0
  • Cancelreply