从左连接获取所有用户ID
Posted
技术标签:
【中文标题】从左连接获取所有用户ID【英文标题】:Get all user ids from left join 【发布时间】:2016-04-08 22:25:40 【问题描述】:我正在从答案表中计算分数。每个答案都有一个难度级别,分数因难度级别而异,所以我编写了一个 sql 查询来计算它我成功计算了分数,但问题是当任何用户没有玩任何一个或多个然后一个难度级别然后列是空的.有关更多说明,请参见下图。
我的查询是
select (IFNULL(k.l1_p*0.5,0)+IFNULL(k.l2_p*1,0)+IFNULL(k.l3_p*2,0)+IFNULL(k.l4_p*2.75,0)+IFNULL(k.l5_p*3.75,0)) as total,k.user_id from (select tab1.l1_p,tab5.user_id,tab2.l2_p,tab3.l3_p,tab4.l4_p,tab5.l5_p from (select count(id) as l1_p,user_id from wp_user_answers where answer=1 and difficulty=1 group by user_id) tab1 left join
-> (select count(id) as l2_p,user_id from wp_user_answers where answer=1 and difficulty=2 group by user_id) tab2 on tab1.user_id=tab2.user_id left join
-> (select count(id) as l3_p,user_id from wp_user_answers where answer=1 and difficulty=3 group by user_id) tab3 on tab3.user_id=tab2.user_id left join
-> (select count(id) as l4_p,user_id from wp_user_answers where answer=1 and difficulty=4 group by user_id) tab4 on tab3.user_id=tab4.user_id left join
-> (select count(id) as l5_p,user_id from wp_user_answers where answer=1 and difficulty=5 group by user_id) tab5 on tab4.user_id=tab5.user_id) k;
这个查询的结果是
您可以看到user_id :169
变为 Null。我想要所有的user_id
【问题讨论】:
【参考方案1】:无需LEFT JOIN,直接使用聚合函数和条件语句即可得到想要的结果。
试试这个:
SELECT user_id,
(SUM(CASE WHEN difficulty = 1 THEN 1 ELSE 0 END) * 0.5 +
SUM(CASE WHEN difficulty = 2 THEN 1 ELSE 0 END) * 1.0 +
SUM(CASE WHEN difficulty = 3 THEN 1 ELSE 0 END) * 2.0 +
SUM(CASE WHEN difficulty = 4 THEN 1 ELSE 0 END) * 2.75 +
SUM(CASE WHEN difficulty = 5 THEN 1 ELSE 0 END) * 3.75
) AS total
FROM wp_user_answers
WHERE answer = 1
GROUP BY user_id;
【讨论】:
非常感谢您的简单回答。以上是关于从左连接获取所有用户ID的主要内容,如果未能解决你的问题,请参考以下文章