Case when then, but with AND condition inside when and before then

后端 未结 3 2081
天命终不由人
天命终不由人 2021-02-13 12:25

In the below query I want to add an AND condition inside the CASE\'s WHEN and before THEN is that possible?

for example WHEN \'r\' AND table1.name=\"jones\" THEN \'very

相关标签:
3条回答
  • 2021-02-13 12:47

    Anything that evaluates to a boolean (true or false) can go in the WHEN condition of a CASE statement. So you can replace 'r' with:

    ('r' AND table1.name='jones')

    Thinking about this more, you might have to lose the table1.event after CASE

    SELECT table1.id, table1.name,
        CASE 
            WHEN (table1.event = 'r' AND table1.name='Jones') THEN 'very high'
            WHEN table1.event = 't' THEN 'very low'
            ELSE (SELECT table2.risk 
                  FROM table2 
                  WHERE table2.value <= table1.value 
                  ORDER BY table2.value DESC LIMIT 1)
        END AS risk
    FROM table1
    ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
    
    0 讨论(0)
  • 2021-02-13 12:51

    You can rewrite your statement like this to accomplish what you want

    SELECT table1.id, table1.name,
       CASE 
         WHEN table1.event = 'r' AND table1.name = 'jones' THEN 'very high'
         WHEN table1.event = 't' AND table1.name = 'smith' THEN 'very low'
         ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
               ORDER BY table2.value DESC LIMIT 1)
       END AS risk
    FROM table1
    ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
    

    notice that you need to remove table1.event after the CASE statement. documentation here

    0 讨论(0)
  • 2021-02-13 13:08

    Switch from case <column> when <value> then ... to case when <condition> then ...:

    CASE 
    WHEN table1.event = 'r' AND table1.active = 1 THEN 'very high'
    ...
    
    0 讨论(0)
提交回复
热议问题