MySQL从同一个连接表中的多个列获取COUNT

时间:2018-03-21 18:05:43

标签: mysql join count sum

我有两张桌子:

  • 用户
  • 消息(其中包含 id_user AND id_user_from

我需要一个有关用户的基本信息列表,以及3个特殊列:

  • 用户收到的COUNT条消息
  • 用户发送的COUNT条消息
  • 用户消息的所有视图(发送和接收)的总和

这是我目前的查询:

SELECT
SUM(case when message.id_user = user.id_user THEN 1 ELSE 0 END) AS q_received,
SUM(case when message.id_user_from = user.id_user THEN 1 ELSE 0 END) AS q_sent,
SUM(message.views) AS views,
user.id_user AS id_user, user.name AS name, user.lastname AS lastname, user.date_login AS date_login
FROM user
    LEFT JOIN message ON message.id_user = user.id_user
ORDER BY user.date_login DESC

总和都是错的。这是sqlfiddle,包含所有必需的表和一些记录作为示例: http://sqlfiddle.com/#!9/4fd838/2

谢谢!

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

select t1.num as q_received, t2.num as q_sent, u.id_user from user u
left join (
 select count(*) as num, id_user from message group by id_user
) t1 on t1.id_user = u.id_user
left join (
 select count(*) as num, id_user_from from message group by id_user_from
) t2 on t2.id_user_from = u.id_user

答案 1 :(得分:1)

我会像下面这样做:

table_a
    table_a_id number(13,0)

table_b
    table_b_id number(13,0)

table_a_b
    table_a_b_id number(13,0)
    fk_table_a_id number(13,0)
    fk_table_b_id number(13,0)