MySQL加入案例

时间:2014-03-28 10:27:30

标签: mysql sql

我有这个查询,

SELECT
table1.*,
CASE 1
WHEN 1 THEN table2.t2
WHEN 2 THEN table3.t3
END AS t_value

FROM table1

CASE 1
WHEN 1 THEN LEFT JOIN table2 ON table1.id = table2.table1_id
WHEN 2 THEN LEFT JOIN table3 ON table1.id = table3.table1_id
END

我有3个不同的表,table1是基表,我需要加入其中一个表(由一个案例决定)

2 个答案:

答案 0 :(得分:0)

您可以尝试下面的动态查询(不是一个只是一个样本)

declare @tablename varchar(30)
declare @query varchar(500)

if(condition = 1)
set @tablename = table2.t2
else 
set @tablename = table3.t3

set @query = 'SELECT
table1.*
FROM table1
join'

set @query = concat(@query,@tablename)

sp_executesql @query

答案 1 :(得分:0)

如果只考虑1个字段,就像这样(我不是MySQL用户)? :

SELECT
  table1.*,
  CASE (row_condition)
   WHEN 1 THEN (SELECT table2.t2 FROM table1 t1
                  LEFT JOIN table2 ON t1.id = table2.table1_id)
   WHEN 2 THEN (SELECT table3.t3 FROM table1 t1
                  LEFT JOIN table3 ON t1.id = table3.table1_id)
  END AS t_value
FROM table1

您可能需要重新加工JOINS,考虑它是否返回1行或更多(因此在每个子选择结束时使用LIMIT 1),' COALESCE'在NULL等情况下