如果condition为true则执行query1,否则执行query2

时间:2018-04-15 10:40:44

标签: mysql sql

if(condition ,select t1.a,t1.b from t1 join t2 on t2.c=t1.a, select t1.a,t1.b from t1) 

但是当我执行它时会显示错误如何克服以及如何获得结果

2 个答案:

答案 0 :(得分:1)

if()可以是SQL语句中使用的函数。我不鼓励这种用法,因为标准结构是case

if也可以是控制流构造。但是,这仅在编程块中允许(想想存储过程和触发器)。

以下是在单个查询中执行所需操作的两种方法:

select t1.a, t1.b
from t1 join
     t2
     on t2.c = t1.a
where condition
union all
select t1.a, t1.b
from t1
where not (condition);

或者:

select t1.a, t1.b
from t1
where (not condition) or
      exists (select 1 from t2 where t2.c = t1.a);

请注意,这两个都假设condition未评估为NULL(尽管这很容易包含在逻辑中)。

答案 1 :(得分:0)

首先提到你的完整SQL语句, IF的文档是

IF search_condition THEN statement_list
    [ELSEIF search_condition THEN statement_list] ...
    [ELSE statement_list]
END IF

你的select语句在哪里?