MYSQL CASE THEN statement with multiple values

前端 未结 4 968
终归单人心
终归单人心 2021-02-07 08:00

I am trying go select multiple values with CASE statement. I noticed we cannot do

CASE 
    WHEN wall.type=\"bk\" 
    THEN books.id1,books.id2, //         


        
4条回答
  •  生来不讨喜
    2021-02-07 08:32

    And everything can be done, but it always depends on what you want to do. Below I'll show you a working example right after you have to take the data as an array and do what you want.

    CREATE TABLE wall (`ident` int,`type` varchar(2), `order` int);
    INSERT INTO wall (`ident`, `type`, `order`) VALUES
        (40,'bk', 1),
        (41,'bk', 5),
        (42,'rt', 2),
        (43,'bk', 3),
        (44,'rt', 1);
    
    CREATE TABLE books (`ident` int,`id1` int, `time` varchar(8), `id2` int);
    INSERT INTO books (`ident`, `id1`, `time`, `id2`) VALUES
        (40, 10, '18:07:00', 20),
        (43, 11, '05:00:00', 21),
        (44, 12, '21:01:00', 22),
        (41, 13, '10:00:00', 23),
        (42, 14, '23:10:00', 24);
    #--------------------------
    SELECT 
      CASE 
        WHEN wall.type='bk' 
        THEN  CONCAT(books.id1,'-',books.id2) 
     END AS column_1
    
    FROM wall JOIN books ON books.ident = wall.ident GROUP BY wall.ident ORDER BY wall.ident ASC;
    

    Print:

     column_1
    1   10-20
    2   13-23
    3   NULL
    4   11-21
    5   NULL
    

    Solution in action via this link: http://rextester.com/LHPI38373

提交回复
热议问题