在IF ELSE条件下使用Union All

时间:2017-10-10 12:19:16

标签: mysql stored-procedures

我想将查询结果与来自IF ELSE条件的另一个查询结果联合起来。以下是我的询问:

set @x=0;
set @y=1;
select 33 as A from dual
union all
IF @x=@y then 
select 44 as A from dual 
else 
select 55 as A from dual
ELSE IF;

2 个答案:

答案 0 :(得分:2)

您可以在不需要存储过程的情况下执行此操作。 使用CASE功能。

<强>查询

SET @x = 0;
SET @y = 1; 

SELECT 33 AS A FROM DUAL

UNION ALL 

SELECT 
 CASE 
   WHEN @x = @y 
   THEN 44
   ELSE 55 
 END AS a
FROM DUAL 

<强>结果

     A  
--------
      33
      55

<强>查询

SET @x = 0;
SET @y = 0; 

SELECT 33 AS A FROM DUAL

UNION ALL 

SELECT 
 CASE 
   WHEN @x = @y 
   THEN 44
   ELSE 55 
 END AS a
FROM DUAL 

<强>结果

     A  
--------
      33
      44

答案 1 :(得分:2)

您只需将其添加到where子句即可。如下所示

function UpdateDetails() {
    var file_data = $('#Photo').get('0').files[0];
    var fd = new FormData();
    fd.append("Photo", file_data);
    fd.append("email", $('#email').val().trim());
    fd.append("Name", $('#Name').val().trim());
    $.ajax({
        url: "/Home/Test",
        method: "POST",
        contentType: false,
        processData: false,
        data:fd,
        success: function (data) {
        },
        error: function (response) {
        }
    });
};

已更新:您可以使用如下的存储过程。

set @x=0;
set @y=0;
select 33 as A from dual
union all 
select 44 as A from dual 
where 
@y = @x  
union all
select 55 as A from dual
where 
@y != @x