Cosytyle Cosytyle - 21 days ago 15
MySQL Question

Adding condition in where conditionally

I can't seem to find a proper solution for this. Here's the scenario I want to
add a condition if the parameter is 0. Looks something like

SELECT * FROM TABLE WHERE name = @name AND
//this is the part I dont know but I want something like
IF(@id = 0)
{
//do nothing
}else{
id = @id
}

Answer

In MySQL, IF is a function (it's like the ternary operator in C and PHP). You can return TRUE from it in the case where you don't need to do anything.

SELECT *
FROM Table
WHERE name = @name
AND IF(@id = 0, TRUE, id = @id)

Another way to do it is with OR:

WHERE name = @name AND (@id = 0 OR id = @id)
Comments