MySQL IF在SWITCH CASE语句中

时间:2015-08-31 14:04:30

标签: mysql

我正在尝试在select查询中的CASE WHERE中放入几个if语句来控制顺序。这是一个简化版本,仍然给我一个语法错误。

SELECT stt_stid, st_stid, st_prid, st_first, st_last, YEAR(st_graduation)
  FROM sttlink
  INNER JOIN student ON stt_stid = st_stid
  WHERE stt_prid = 3920103
  GROUP BY stt_stid
  ORDER BY
    CASE 
      WHEN (MONTH(now())>='9')
        THEN    
          if(YEAR(st_graduation) = YEAR(now()), 0, 1),
          st_graduation
      WHEN (MONTH(now())<'9')
        THEN
          if(YEAR(st_graduation) >= YEAR(now()), 1, 0),
          st_graduation
      END;

错误信息(Navicat)是:

[Err] 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 '
      st_graduation
  WHEN (MONTH(now())<'9')
    THEN
    ' at line 13

这里有更多的东西(感谢目前为止的看法!)。这是我原来的工作版本。问题是我需要有两个不同的顺序条款 - 一个月是9月到12月,另一个是1月到8月。

ORDER BY if(YEAR(st_graduation)>=YEAR(now()), 0, 1),
        if(YEAR(st_graduation)>=YEAR(now()), 10000, datediff(now(),st_graduation)),
        st_graduation

上述情况很好,如果它是1月至8月,但我需要在9月至12月期间略有不同。

Rahul的回答非常接近。现在我要在声明中写下第二个案例:

ORDER BY 
CASE 
  WHEN (MONTH(now()) >= '9')
    THEN    
      CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 0 ELSE 1 END,
      CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 10000 ELSE (datediff(now(),st_graduation)) END
  WHEN (MONTH(now()) < '9')
    THEN
      CASE WHEN YEAR(st_graduation) >= YEAR(now()) THEN 1 ELSE 0 END,
      CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 10000 ELSE (datediff(now(),st_graduation)) END
  END, st_graduation;

我是否应该创建第二个单独的“主要”案例/何时 - 条款相同但只有第二个案例陈述?

2 个答案:

答案 0 :(得分:1)

我认为您打算使用Nested CASE表达式

执行以下操作
ORDER BY
    CASE 
      WHEN MONTH(now()) >= '9' THEN    
          CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 0 ELSE 1 END

因此,在您的情况下,ORDER BY子句应该看起来像

  ORDER BY
    CASE 
      WHEN (MONTH(now()) >= '9')
        THEN    
          CASE WHEN YEAR(st_graduation) = YEAR(now()) THEN 0 ELSE 1 END          
      WHEN (MONTH(now()) < '9')
        THEN
          CASE WHEN YEAR(st_graduation) >= YEAR(now()) THEN 1 ELSE 0 END
      END, st_graduation;

答案 1 :(得分:1)

怎么样

SELECT stt_stid, st_stid, st_prid, st_first, st_last, YEAR(st_graduation)
  FROM sttlink
  INNER JOIN student ON stt_stid = st_stid
  WHERE stt_prid = 3920103
  GROUP BY stt_stid
  ORDER BY
    CASE 
      WHEN (MONTH(now())>='9' and YEAR(st_graduation) = YEAR(now()))
        THEN 
          st_graduation
      WHEN (MONTH(now())<'9' and YEAR(st_graduation) >= YEAR(now()))
        THEN
          st_graduation
      END;