代码之家  ›  专栏  ›  技术社区  ›  sixtyfootersdude

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

  •  0
  • sixtyfootersdude  · 技术社区  · 14 年前

    假设这个命令: 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 回复  |  直到 14 年前
        1
  •  1
  •   Niet the Dark Absol    14 年前
    SELECT
        sessionID,
        SessionLength,
        IF( SessionLength > 10, "BIG",
            IF( SessionLength < 1, "SMALL", "MEDIUM")) AS Size
    FROM mytable;
    

    高温高压

        2
  •  2
  •   Ramon    14 年前

    对,

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