简体   繁体   中英

oracle query - additional where condition depending on a field

Its hard to explain what exactly i mean using words so ill write a query similar to what i have at the moment.

SELECT * 
FROM table t 
WHERE t.something = 'something' 
  AND CASE WHEN t.name = 'john' THEN 'smith' ELSE t.lastname END = t.lastname

Basicly depending if a field is what i want it to be (name = john) i want to add another condition (lastname = smith). If that field isnt what i want it to be (name != john) then no condition is needed (lastname can be whatever) This code works but for me it seems to be kind of a hack. My question is if this can be done more easily or more prettily? Thanks in advance :)

You can do this without the case :

WHERE t.something = 'something' AND
      (t.lastname = 'smith' or t.name <> 'john')

You can place the entire test within the CASE statement:

AND CASE WHEN t.name = 'john' THEN t.lastname = 'smith' ELSE True

(I don't remember my Oracle so well. True may not be the correct term here.)

Now the result of the CASE is a truth value rather than a value to be tested against t.lastname .

It is equivalent to:

WHERE
  t.name = 'john' AND t.lastname = 'smith' 
  OR t.name <> 'john'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM