Tobi Schweiger
Tobi Schweiger

Reputation: 11

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 (e.g. '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.

Upvotes: 1

Views: 1395

Answers (2)

KAD
KAD

Reputation: 11102

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.

Upvotes: 0

Jacob Lambert
Jacob Lambert

Reputation: 7679

Just add a null condition to your WHERE clause:

WHERE Location = 'US'
    OR Location IS NULL

Upvotes: 4

Related Questions