关于SELECT中的IF语句的MySQL查询出错

时间:2014-06-25 19:25:45

标签: mysql mysql-python

我无法弄清楚以下查询的错误:

SELECT   t_sh.source_file_id,
         t_sh.id,
         MAX(t_sh.master_event_id),
         IF(t_sh.content REGEXP '[;}[:space:]]break;', 'true', 'false') AS break,
         IF(t_sh.content REGEXP '[;}[:space:]]break ', 'true', 'false') AS break_label,
         IF(t_sh.content REGEXP '[;}[:space:]]continue;', 'true', 'false') AS continue,
         IF(t_sh.content REGEXP '[;}[:space:]]throw ', 'true', 'false') AS throw,
         IF(t_sh.content REGEXP '[;}[:space:]]return;', 'true', 'false') AS void_return
FROM     source_histories AS t_sh,
         (   SELECT DISTINCT source_file_id
             FROM source_histories
             WHERE content <> NULL 
                 AND content REGEXP '[;}[:space:]]break;|[;}[:space:]]break |[;}[:space:]]continue;|[;}[:space:]]throw |[;}[:space:]]return;'
         ) AS t_uniqueSFI
WHERE t_sh.source_file_id = t_uniqueSFI.source_file_id;

使用python的MySQLdb运行时出现以下错误:

_mysql_exceptions.ProgrammingError: (1064, "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
'continue,\n\t\t\t\t\t\t\tIF(t_sh.content REGEXP '[;}[:space:]]throw ', 'true', 'false') ' at line 6")

我是SQL的新手,非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

问题在于

IF(t_sh.content REGEXP '[;}[:space:]]continue;', 'true', 'false') as continue

继续是reserved word,你需要反击一下

IF(t_sh.content REGEXP '[;}[:space:]]continue;', 'true', 'false') as `continue`

当您的查询到达此行时,mysql会发生什么

mysql> select IF(uname REGEXP '[;}[:space:]]continue;', 'true', 'false') 
AS continue from test ;
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 'continue from test' at line 1

现在,如果我在测试表上使用反引号,那么

mysql> select IF(uname REGEXP '[;}[:space:]]continue;', 'true', 'false')
 AS `continue` from test ;
+----------+
| continue |
+----------+
| false    |
| false    |
| false    |
| false    |
| false    |
| false    |
| false    |
+----------+