简体   繁体   English

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

[英]MySQL: SELECT an extra column categorizing another column based on IF statements

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

Generates this table: 生成此表:

+-----------+---------------+
| 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)

But I want to generate a table like this: 但是我想生成一个这样的表:

+-----------+---------------+--------+
| 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)
  • Something is big when it's SessionLength > 10 SessionLength > 10时,东西big
  • Something is medium when it's SessionLength <= 10 AND SessionLength >=1 SessionLength <= 10 AND SessionLength >=1时,表示medium
  • Something is small whne it's SessionLength > 1 如果SessionLength > 1那么事情就small

Conceptually what I want to do is this: 从概念上讲,我要做的是:

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

Is there an easy way to do this? 是否有捷径可寻?

Yes, 是,

SELECT
   sessionID, SessionLength,
   CASE WHEN SessionLength > 10 THEN 'BIG'
        WHEN SessionLength < 1 THEN 'SMALL'
        ELSE 'MEDIUM'
   END 
FROM mytable;
SELECT
    sessionID,
    SessionLength,
    IF( SessionLength > 10, "BIG",
        IF( SessionLength < 1, "SMALL", "MEDIUM")) AS Size
FROM mytable;

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM