[英]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. 我需要根据条件执行不同的SELECT语句。
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. 换句话说,我需要根据条件添加一个额外的WHERE子句,但是问题归结为根据条件是true还是false选择不同的SELECT子句。
SELECT id FROM table WHERE variable=1 OR <condition>
case statements can be used as well... case语句也可以使用...
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). 您可能需要在case语句中使用不同的逻辑,但这是说当变量具有值(非null)时,请使用where子句变量= @variable,否则使用1 = 1(不带任何过滤器)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.