MYSQL CASE THEN statement with multiple values

前端 未结 4 972
终归单人心
终归单人心 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

    0 讨论(0)
  • 2021-02-07 08:38

    No. CASE statement can only return a single value, so the only way to achieve what you want is duplicate the case ...

    The database server should be optimized and perform only one time the check on the same condition ...

    0 讨论(0)
  • 2021-02-07 08:42

    No, it is just a single value. Additionally, it is contradictory to use "multiple columns" and name those multiple columns as column_1, right? :)

    You can use another column to store the other id with (a similar case) and use nulls to represent the else values, just like you're doing now.

    Example:

    CASE 
        WHEN wall.type="bk" 
        THEN books.id1
    END as column_1,
    CASE 
        WHEN wall.type="bk" 
        THEN books.id2
    END as column_2
    

    Check the official documentation for more information.

    0 讨论(0)
  • 2021-02-07 08:48

    According to documentation mysql_doc; you can use you can use the other syntax of case for what you wanted.

    case
     WHEN FIND_IN_SET(edu, "1,1st,2,2nd,3,3rd,4,4th,5,5th,pri,primary,primery") THEN
      SET memEdu = "Primary";
     WHEN FIND_IN_SET(edu, "intermediate,inter,f.a,fa,fac,f.a.c,f.sc,fsc,1rd year,2rd year,3rd year") THEN
      SET memEdu = "Intermediate";
    End case;
    
    0 讨论(0)
提交回复
热议问题