MySQL:选择一个额外的列,根据IF语句对另一列进行分类

时间:2010-11-15 12:11:30

标签: mysql select

假设此命令:SELECT sessionID, SessionLength FROM mytable;

生成此表:

+-----------+---------------+
| sessionID | SessionLength |
+-----------+---------------+
|         1 | 00:20:31      | 
|         2 | 00:19:54      | 
|         3 | 00:04:01      | 

  ...
|      7979 | 00:00:15      | 
|      7980 | 00:00:00      | 
|      7981 | 00:00:00      | 
+-----------+---------------+
7981 rows in set (0.92 sec)

但我想生成一个这样的表:

+-----------+---------------+--------+
| sessionID | SessionLength | Size   |
+-----------+---------------+--------+
|         1 | 00:20:31      | BIG    |
|         2 | 00:19:54      | BIG    |
|         3 | 00:04:01      | MEDIUM |

  ...
|      7979 | 00:00:15      | SMALL  |
|      7980 | 00:00:00      | SMALL  |
|      7981 | 00:00:00      | SMALL  |
+-----------+---------------+--------+
7981 rows in set (0.92 sec)
  • big
  • 时,某些内容为SessionLength > 10
  • medium
  • 时,某些内容为SessionLength <= 10 AND SessionLength >=1
  • 某事small SessionLength > 1

从概念上讲,我想做的是:

SELECT 
   sessionID, 
   SessionLength,
   (SessionLength > 10 ? "BIG" : (SessionLength < 1 : "SMALL" : "MEDIUM"))
FROM mytable;

有一种简单的方法吗?

2 个答案:

答案 0 :(得分:2)

是的,

SELECT
   sessionID, SessionLength,
   CASE WHEN SessionLength > 10 THEN 'BIG'
        WHEN SessionLength < 1 THEN 'SMALL'
        ELSE 'MEDIUM'
   END 
FROM mytable;

答案 1 :(得分:1)

SELECT
    sessionID,
    SessionLength,
    IF( SessionLength > 10, "BIG",
        IF( SessionLength < 1, "SMALL", "MEDIUM")) AS Size
FROM mytable;

HTH