zxzak
zxzak

Reputation: 9446

MySQL Query - SELECT based on condition

I cannot find an answer to this seemingly easy problem. I need to execute a different SELECT statement based on a condition.

A simple example :

if <condition>

SELECT id FROM table;

otherwise

SELECT id FROM table WHERE variable=1;

In other words I need to add an additional WHERE clause depending on the condition, however the problem boils down to choosing a different SELECT clause based on whether the condition is true or false.

Upvotes: 0

Views: 2087

Answers (2)

Twelfth
Twelfth

Reputation: 7180

case statements can be used as well...

SELECT id FROM table
where case when variable is not null then variable else 1 end
=
case when variable is not null then @variable else 1 end

You'll probably want different logic in the case statements, but this is saying when variable has a value (not null) then use the where clause variable = @variable, else 1=1 (which brings back all rows / no filter).

Upvotes: 0

Menno
Menno

Reputation: 12621

SELECT id FROM table WHERE variable=1 OR <condition>

Upvotes: 1

Related Questions