mysql IF ELSE语句语法错误

时间:2017-07-04 11:24:06

标签: mysql

我有以下查询:

    SELECT 
     * 
FROM 
    `hssData` 
WHERE 
    `group` = 'LGA_737_CA' 
    AND (
        `pos` = 'CA' OR `pos` = 'RC'
    ) 
    AND (
        `depTimeInt` >= 0 AND `depTimeInt` <= 1440
    ) 
    AND (
        `arrTimeInt` >= 1050 OR `arrTimeInt` <= 45
    ) 
    AND `days` >= 1 
    AND `days` <= 2 
ORDER BY 
    `depTime` ASC 
LIMIT 
    0, 100

...除了我想要的arrTimeInt <= 45时:

`days` >= 1 AND `days` <= 1

而不是

`days` >= 1 AND `days` <= 2

我试过了:

       SELECT 
    * 
FROM 
    `hssData` 
WHERE 
    `group` = 'LGA_737_CA' 
    AND (
        `pos` = 'CA' OR `pos` = 'RC'
    ) 
    AND (
        `depTimeInt` >= 0 AND `depTimeInt` <= 1440
    ) 
    AND (
        `arrTimeInt` >= 1050 OR `arrTimeInt` <= 45
    ) 
    AND (
        IF (`arrTimeInt` < 45) THEN (
            `days` <= 1 AND `days` <= 3
        ) ELSE (
            `days` <= 1 AND `days` <= 2
        )
    ) 
ORDER BY 
    `depTime` ASC 
LIMIT 
    0, 100

但这会引发语法错误。

我无法获得正确的语法。我究竟做错了什么?语法错误是:

  

#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法   ')附近()               days&lt; = 1               AND days&lt; = 2           )ELSE(               days&lt; = 1               A'在第20行

1 个答案:

答案 0 :(得分:0)

您正在尝试在非程序性环境中使用procedural construct

在SELECT(或UPDATE或DELETE)语句中,您需要使用IF function(或CASE)。因此:

 SELECT 
   * 
 FROM 
    `hssData` 
 WHERE 
  `group` = 'LGA_737_CA' 
  AND (
    `pos` = 'CA' 
    OR `pos` = 'RC'
  ) 
  AND (   // brackets in this clause are redundant
    `depTimeInt` >= 0 
    AND `depTimeInt` <= 1440
  ) 
  AND (
    `arrTimeInt` >= 1050 
    OR `arrTimeInt` <= 45
  ) 
  AND `days` >= 1 
  AND `days` <= IF(`arrTimeInt` <= 45, 1, 2)
ORDER BY 
  `depTime` ASC 
LIMIT 
  0, 100