mysql错误时的总和

时间:2018-07-11 01:43:13

标签: mysql sql sum case

我写过:

select 
    sum(case when is_trigger = "1" and when lh.ladder_change = "1" then 1 else 0 end),
    lh.member_id as "SFID"
From
  leeds_so.leenk_ladder_config as lc
  left join leeds.leenk_ladder_history as lh on lc.id = lh.ladder_config_id 

group by lh.member_id

limit 100;

我遇到错误:

ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.member_id as "SFID"
From
  leeds_so.leenk_ladder_config as lc
  left join le' at line 2

我不确定这是什么错误。谁能帮我吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

and when是无效的SQL。放下when。您可以进一步简化逻辑:

select sum(is_trigger = 1 and lh.ladder_change = 1),
       lh.member_id as SFID
From leeds_so.leenk_ladder_config lc left join 
     leeds.leenk_ladder_history lh
     on lc.id = lh.ladder_config_id 
group by lh.member_id
limit 100;

注意:

  • MySQL将布尔表达式视为数字,其中“ 1”为真,“ 0”为假。因此,不需要case
  • 您可能打算使用inner join或切换表格。您正在按 second 表中的一列进行汇总。如果没有匹配项,则为NULL
  • 双引号不是SQL中字符串的适当分隔符。对字符串使用单引号。
  • 我认为常量实际上是数字,因此根本不需要引用。