有条件地连接两列

时间:2018-02-07 21:09:11

标签: mysql sql

我有名为 table_1 的MySQL表:

mysql> select * from table_1;
+----------+-----------+----------+-------+
| col_1    | col_2     | col_3    | col_4 |
+----------+-----------+----------+-------+
|      123 | ABCD      | TTTTT    |     3 |
|    46542 | ABCD/HIJ  | AAAAAAAA |     9 |
|       23 | ABCDEFGH  | CCC      |    45 |
|     5675 | ABCD/HIJ  | NNNN     |     0 |
|    65165 | NJFD      | QQQQ     |     0 |
|   165464 | NULL      | HHH      |     8 |
| 16546541 | ABCABC    | LLLLLL   |     0 |
|   764316 | ABCD/BBJH | NULL     |     3 |
|     3125 | NULL      | EEEEEE   |    91 |
+----------+-----------+----------+-------+
9 rows in set (0.00 sec)

DDL:

CREATE TABLE IF NOT EXISTS table_1 (
  col_1 INT(11) NOT NULL,
  col_2 VARCHAR(45) DEFAULT NULL,
  col_3 VARCHAR(10) DEFAULT NULL,
  col_4 INT(11) NOT NULL
);

插入数据:

INSERT INTO table_1(col_1,col_2,col_3,col_4)
VALUES (123,'ABCD','TTTTT',3),
       (46542,'ABCD/HIJ','AAAAAAAA',9),
       (23,'ABCDEFGH','CCC',45),       
       (5675,'ABCD/HIJ','NNNN',0),
       (65165,'NJFD','QQQQ',0),
       (165464,NULL,'HHH',8),
       (16546541,'ABCABC','LLLLLL',NULL),
       (764316,'ABCD/BBJH',NULL,3),
       (3125,NULL,'EEEEEE',91);

我想要做的是选择col_1和一个新的MySQL生成的第二列,比如col_new。

  1. 如果col_2为NULL,则col_new也应为NULL。
  2. 如果col_2为非NULL但col_3为NULL,则col_new也应为NULL。
  3. 如果col_2和col_3都是非NULL,则col_new应与col_3相同。
  4. 3.如果col_2和col_3都为NOT NULL且col_3 ='CCC',则col_new应为concat(col_3, 'v', col_4),在这种情况下应为'CCCv45'。
  5. 我知道我必须使用concat,例如select col_1, concat(col_3, 'v', col_4) from table_1

    但我怎样才能实现上述所有4个条件?

2 个答案:

答案 0 :(得分:3)

编写CASE表达式的另一种方法是:

select t.*,
    case when col_2 is null then null
         when col_3='CCC' then concat(col_3, 'v', col_4)
         else col_3
    end as new_col2     
from table_1 t

答案 1 :(得分:1)

SELECT col_1, 
CASE 
WHEN (col_2 IS NULL) OR (col_2 IS NOT NULL AND col_3 IS NULL) THEN NULL
WHEN col_2 IS NOT NULL AND col_3 = 'CCC' THEN concat(col_3, 'v', col_4)
WHEN col_2 IS NOT NULL AND col_3 IS NOT NULL THEN col_3
END
FROM table_1

http://sqlfiddle.com/#!9/eb2550/5

Soltution 2

SELECT 
    col_1, 
    IF(
        (col_2 IS NULL) 
        OR (
            col_2 IS NOT NULL 
            AND col_3 IS NULL
        ), 
        NULL, 
        (
            IF(
                col_2 IS NOT NULL 
                AND col_3 = 'CCC', 
                concat(col_3, 'v', col_4), 
                col_3
            )
        )
    ) 
FROM 
    table_1

http://sqlfiddle.com/#!9/eb2550/9