jhon dano
jhon dano

Reputation: 658

Ho to write a query with IF inside of WHERE clause?

I am wondering if its possible to write a query like this:

PHP variables to do comparison: $column2 = A; $column3 = null;

SELECT * FROM table1 
WHERE col1 = 1
IF(col2 IS NOT NULL)
col2 = $column2
AND 
IF(col3 IS NOT NULL)
col3 = $column3

The general idea is to match array of objects against a dynamic filter defined in MySQL table. But i only want to compare the columns which are not null.

Can anyone help or guide me to a better way of doing this? Thanks

Upvotes: 0

Views: 29

Answers (2)

GGadde
GGadde

Reputation: 391

Try if this helps

SELECT * FROM table1 
WHERE col1 = 1
AND col2 = IIF(col2 IS NOT NULL,$column2,col2)
AND col3 = IIF(col3 IS NOT NULL,$column3,col3)

Upvotes: 0

Luca Lupidi
Luca Lupidi

Reputation: 164

I think this could be right

SELECT * FROM table1 
WHERE col1 = 1
AND
IFNULL(col2, $column2)=$column2
AND 
IFNULL(col3, $column3)=$column3;

but I would create the where clause with php code to dinamically create the SQL statement

Upvotes: 1

Related Questions