从左连接获取所有用户ID

时间:2016-01-05 06:59:48

标签: mysql sql select left-join aggregate-functions

我正在从答题表中计算得分。每个答案都有一个难度级别,分数与难度级别不同所以我写了一个sql查询来计算它我成功计算了分数但问题是当任何用户没有玩过任何一个或多个一个难度级别然后列来了null 。有关更多说明,请参见下图。 Sql table snapshot

我的查询是

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;

此查询的结果是

enter image description here

你可以看到user_id :169变为空。我想要所有user_id

1 个答案:

答案 0 :(得分:3)

无需使用 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;