在mysql中出现错误,错误在哪里?

时间:2012-09-16 03:22:05

标签: mysql sql

我想知道以下代码有什么问题:

cursor.execute("""SELECT calldate, dst, billsec, accountcode, disposition, 
                case when cast(substring(dst,4,1), unsigned) <= 5 then
                        billsec/60*%s as total
                else
                        billsec/60*%s as total
                end case
                FROM cdr where calldate >= '%s' and calldate < '%s' and disposition like '%s' and accountcode = '%s' and dst like '%s'""" %(rate_fixo, rate_movel, start_date, end_date, status, accountcode, destino))

尝试过这种方式并且无法正常工作:

cursor.execute("""SELECT calldate, dst, billsec, accountcode, disposition,
    case when cast(substring(dst,4,1), unsigned) <= 5 then 
        billsec/60*%s 
    else 
        billsec/60*%s 
    end as total
    FROM cdr where calldate >= '%s' and calldate < '%s' and disposition like '%s' 
    and accountcode = '%s' and dst like '%s'""" 
    %(rate_fixo, rate_movel, start_date, end_date, status, accountcode, destino))

错误:

“您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在'unsigned'附近使用正确的语法&lt; = 5然后billsec / 60 * 0.1 else billsec / 60 * 0.2 end作为总行FROM cdr w'在第1行“)

1 个答案:

答案 0 :(得分:2)

MySQL有两种case语句语法。一个用于queries,一个用于stored procedures。您在查询中使用sproc版本,导致错误。查询版本中没有“最终案例”:

SELECT ..., CASE WHEN ... THEN... END 
                                      ^---no 'case' here
FROM ...

---跟进

同样,你不能对案例的组成部分进行别名 - 这会动态地改变字段的名称,具体取决于案例的评估结果。您只能为ENTIRE案例陈述添加别名:

SELECT ..., CASE WHEN ... THEN ... END AS total
                                      ^^^^^^^^^

e.g。

mysql> select case when 1=1 then 'a' else 'b' end case, 'hello';
                                                  ^^^^---syntax error         
ERROR 1064 (42000): 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 'case, 'hello'' at line 1

mysql> select case when 1=1 then 'a' else 'b' end, 'hello';     
+-------------------------------------+-------+
| case when 1=1 then 'a' else 'b' end | hello |
+-------------------------------------+-------+
| a                                   | hello |
+-------------------------------------+-------+
1 row in set (0.00 sec)

mysql> select case when 1=1 then 'a' as 'a_val' else 'b' as 'b_val' end, 'hello
';
                                    ^^^^^^^^^^^--error  ^^^^^^^^^^^--- error
ERROR 1064 (42000): 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 'as 'a_val' else 'b' as 'b_val' end, 'hello'' at line 1

mysql> select case when 1=1 then 'a' else 'b' end as total, 'hello';           
+-------+-------+
| total | hello |
+-------+-------+
| a     | hello |
+-------+-------+
1 row in set (0.00 sec)