简体   繁体   中英

where clause based on conditions

I have a query where I match a column. The value to be matched may be null or not null (some value exists). The problem arises when the matching takes place. In case value is present the matching like

table.column = somevalue

works fine, but in case the value is null, then the matching needs to be done as

table.column is null

Is there some way that I can choose the condition being used in the WHERE clause based on the value?

Thanks in advance

What about ORing your WHERE clause?

SELECT
*
FROM table
WHERE ((table.column = 123) AND table.column IS NOT NULL))
OR    (table.column IS NULL)

Use a CASE statement, eg:

SELECT
  CASE
    WHEN mycol IS NULL
      THEN 'it is null'
    WHEN mycol = 'foo'
      THEN 'it is foo'
    ELSE 'it is something else'
  END AS col
FROM mytable;

(Note: I don't know what DB you are using, so "IS NULL", "ISNULL", "ISNULL()" might be needed above)

检查MySQL 控制流功能

Try using ISNULL(somevalue, 0). Provided that your "somevalue" table.column does not have 0 is a valid value. Instead of 0 you may use any string/number that will never appear as a valid value in table.column

In ms sql you could do

      declare @match int
      select * from tbl where coalesce(tblValue, @match) = @match

That way you will compare @match with itself when tblValue is null.

Of course you can eliminate the parameter if it is null by switching the matching

      select * from tbl where tblValue = coalesce(@match, tblValue) 

but the latter query may cause the query optimizer to neglect indexes on tblValue, so you should check the execution plan.

I used decode and case statement to solve this problem This has been done in oracle.


    AND DECODE(TSBI.SHIP_TRAIL_STATUS, 
               'L', 
               'TRUE', 
               'C', 
               (SELECT CASE 
                    WHEN TSBI.UPD_ON + 10 >= SYSDATE THEN 
                         'TRUE' 
                     ELSE 
                          'FALSE' 
                      END 
                FROM DUAL)) = 'TRUE'

In this condition I have checked the SHIP_TRAIL_STATUS. In case it returns 'L' the decode function returns TRUE. In case it returns 'C' the decode checks the UPD_ON value. Accordingly this CASE statement return TRUE or FALSE.

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