using CASE in the WHERE clause

前端 未结 4 1876
甜味超标
甜味超标 2021-01-31 08:38

simplified version of my query

SELECT *
FROM logs 
WHERE pw=\'correct\' AND CASE WHEN id<800 THEN success=1 ELSE END 
AND YEAR(timestamp)=2011 
相关标签:
4条回答
  • 2021-01-31 08:53

    You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

    SELECT *
    FROM logs 
    WHERE pw='correct' AND (id>=800 OR success=1)  
    AND YEAR(timestamp)=2011
    

    I also transformed NOT id<800 to id>=800, which is also pretty basic.

    0 讨论(0)
  • 2021-01-31 09:00

    This is working Oracle example but it should work in MySQL too.

    You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

    SELECT empno, ename, job
      FROM scott.emp
     WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
             WHEN job = 'CLERK'   THEN '2' 
             ELSE '0'  END) IN (1, 2)
    
    0 讨论(0)
  • 2021-01-31 09:03
    SELECT *
    FROM logs
    WHERE pw='correct'
      AND CASE
              WHEN id<800 THEN success=1
              ELSE 1=1
          END
      AND YEAR(TIMESTAMP)=2011
    
    0 讨论(0)
  • 2021-01-31 09:08

    You don't have to use CASE...WHEN, you could use an OR condition, like this:

    WHERE
      pw='correct'
      AND (id>=800 OR success=1) 
      AND YEAR(timestamp)=2011
    

    this means that if id<800, success has to be 1 for the condition to be evaluated as true. Otherwise, it will be true anyway.

    It is less common, however you could still use CASE WHEN, like this:

    WHERE
      pw='correct'
      AND CASE WHEN id<800 THEN success=1 ELSE TRUE END 
      AND YEAR(timestamp)=2011
    

    this means: return success=1 (which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise.

    0 讨论(0)
提交回复
热议问题