用于连接三个表的mysql case语句

时间:2014-04-14 07:34:19

标签: mysql

有三个表

table a
table b 
table c

我的查询是:

select a.title,a.id,b.title 
  from table a 
  case when a.type=1 then 
       inner join table a.id=tableb.id end 
  case when a.type=2 then inner join table a.id=table c.id

但是这个查询不起作用。可以帮助正确的方法来获取或执行这种类型的查询

2 个答案:

答案 0 :(得分:1)

你不能在from子句中使用case。为此,您可以使用UNION ALL。例如:

select a.title,a.id,b.title
from table a inner join table b on a.id=b.id
where a.type=1
UNION ALL
select a.title,a.id,c.title
from table a inner join table c on a.id=c.id
where a.type=2

答案 1 :(得分:0)

你不能做类似“如果这是1然后加入其他表而不是2”的话,你必须加入两者并相应地选择:

SELECT
  a.title, 
  a.id, 
  IF (tableb.title IS NOT NULL, tableb.title, tablec.title),
  CASE a.type
    WHEN 1 THEN tableb.id
    WHEN 2 THEN tablec.id
  END
FROM table a
LEFT JOIN tableb ON tablea.id = tableb.id
LEFT JOIN tablec ON tablea.id = tablec.id
相关问题