简体   繁体   中英

MySQL - Ignore 'WHERE' clause if specific column has value

I have quite the long query and I join my primary table with a table that basically contains a plan/package. However, one of the options in the purchase plan table is Location. If the Location is empty, it basically means 'any country'.

Now, if the Location in the plan package (which is joined with the primary table) is null, I still want to select that row. If it isn't null however, I want it to be a different specific value (eg 'US'), basically ensuring that if the location is null, the location where clause isn't include.

Hope that was clear enough, and would appreciate any help.

Just add a null condition to your WHERE clause:

WHERE Location = 'US'
    OR Location IS NULL

You can use CASE WHEN in WHERE clause :

 Select * from tbl1 join tbl2 on tbl1.key = tbl2.key 
 where tbl1.location = CASE when tbl2.location 
 IS NOT NULL tbl2.location ELSE tbl1.location END

In this way, if the location in table 2 is not empty, it will check against location in table 1, otherwise it will set tbl1.location=tbl1.location which is always true.

I hope I understood what you really desired.

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