如果一个条件不存在,则返回值mysql

时间:2019-01-22 07:27:17

标签: php mysql sql

即使值不存在,我也想返回值。例如,id = 245的用户仅在2017年具有值,但是如果数据库中没有数据,则其想法是返回2016年的值0和2018年的值= 0。

SELECT member_id, year,
   SUM(amount_nitrogen) as amount_nitrogen,   
   SUM(amount_potassium) as amount_potassium,
   SUM(amount_phosphorus) as amount_phosphorus,
   SUM(amount_sodium_oxide) as amount_sodium_oxide
   FROM ct 
WHERE year >= 2016 and year <= 2018
GROUP BY  member_id, year

如果用户拥有所有三年的数据:2018、2017、2016,那很好,但是如果用户只有一年的数据,那么我只能得到今年的数据。范围是获取其他2年的数据,并且该数据应为0

1 个答案:

答案 0 :(得分:0)

使用CROSS JOIN生成行,使用LEFT JOIN引入数据:

SELECT m.member_id, y.year,
       COALESCE(SUM(ct.amount_nitrogen), 0) as amount_nitrogen,   
       COALESCE(SUM(ct.amount_potassium), 0) as amount_potassium,
       COALESCE(SUM(ct.amount_phosphorus), 0) as amount_phosphorus,
       COALESCE(SUM(ct.amount_sodium_oxide), 0) as amount_sodium_oxide
FROM (SELECT DISTINCT member_id FROM ct) m CROSS JOIN
     (SELECT 2016 as year UNION ALL SELECT 2017 UNION ALL SELECT 2018
     ) y LEFT JOIN
     ct
     ON ct.member_id = m.member_id AND ct.year = y.year
GROUP BY m.member_id, y.year