如何在mysql的case语句中使用比较运算符

时间:2013-01-01 14:16:24

标签: mysql case

这是我的表数据......

id  days
-----------
1   10
    20
3   30
4   25
5   5

我想要像

这样的结果
id  days    resultcolumn
1    10   less than 10
2    20   less than 20
3    30   less than 30
4    25   less than 30
5    5    less than 10

我使用了查询

SELECT id,days,
  CASE days 
    WHEN days<=10 THEN 'less than 10'
    WHEN days<=20 THEN 'less than 20'
    WHEN days<=30 THEN 'less than 30'
  END AS 'days2'
FROM calender

但我得到的结果数据如

id  days    resultcolumn
1   10    {null}
2    20   {null}
3    30   {null}
4    25   {null}
5    5    {null}

如何在mysql中使用case语句获取原始结果?

4 个答案:

答案 0 :(得分:9)

试试这个:

SELECT
      id,
      days,
      CASE WHEN days<=10 THEN 'less than 10'
           WHEN days<=20 THEN 'less than 20'
           WHEN days<=30 THEN 'less than 30' END AS 'days2'
    FROM calender

答案 1 :(得分:2)

您必须在CASE之后删除几天:

SELECT
  id,
  days,
  CASE WHEN days<=10 THEN 'less than 10'
       WHEN days<=20 THEN 'less than 20'
       WHEN days<=30 THEN 'less than 30' END AS 'days2'
FROM calender

答案 2 :(得分:1)

您可以在没有CASE ... WHEN构造的情况下执行此操作。只需使用简单的数学。

SELECT *, 
    CONCAT('less than ', CEIL(`days`/10)*10) AS `resultcolumn` 
FROM `Table1`

sqlfiddle

这可以防止Branch predication失败。因此它将是faster for large data set

答案 3 :(得分:1)

试试这个:

SELECT id,days,
  CASE  
      WHEN days<=10 THEN 'less than 10'
      WHEN days<=20 THEN 'less than 20'
      WHEN days<=30 THEN 'less than 30'
  END AS 'resultcolumn'
FROM calender