我有两张桌子:
我需要一个有关用户的基本信息列表,以及3个特殊列:
这是我目前的查询:
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
谢谢!
答案 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)