select case when integer=1 then (select col1,col2 from table1)
when integer=2 then (select col11,col22 from table2)
end
子查询是否可以返回多个值,如果不是哪种方法比这更好?
答案 0 :(得分:2)
CASE
适用于标量而不是行。对于你的问题,我会用这个:
IF integer=1
SELECT col1 AS colA, col2 AS colB FROM table1
ELSE IF integer=2
SELECT col11 AS colA, col22 AS colB FROM table2
答案 1 :(得分:1)
也许它不是特别干净,但这应该有效:
SELECT CASE my_table.integer
WHEN 1 THEN table1.col1
ELSE table2.col11
END AS col_1,
CASE my_table.integer
WHEN 1 THEN table1.col2
ELSE table2.col2
END AS col_2
FROM my_table
LEFT OUTER JOIN table1
ON ....
LEFT OUTER JOIN table2
ON ....
...
答案 2 :(得分:1)
您是否使用过MS Sql Server,如果是,您可以试试这个
declare @script nvarchar(400)
select @script = case SomeField -- conditions field
when 1 then 'select * from [TableA]'
when 2 then 'select * from [TableB]'
end
from [TableC] where ...
exec sp_executesql @script
但请注意将用户的任何输入连接到脚本。
答案 3 :(得分:1)
您可以使用union all
:
select col1, col2
from table1
where integer = 1
union all
select col1, col2
from table2
where integer = 2;