搜尋

首頁  >  問答  >  主體

MySQL中如何進行分組和計數?

我正在嘗試編寫一個查詢,提取發送給朋友的未刪除訊息的總數。這是表結構的螢幕截圖:

我想要實現的輸出結果如下:

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

這是我迄今為止嘗試過的查詢:

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 天前621

全部回覆(1)我來回復

  • P粉662802882

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

    你嘗試過類似的事情嗎?

    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;

    回覆
    0
  • 取消回覆