如何在 JOIN 语句中使用 CASE 根据条件连接两个表?

How to use CASE in JOIN statement to join two tables based on condition?

我有三个 table:emailcustomer_newcustomers_old。 现在在 email table 中有一个名为 type 的字段,其中包含 01.
因此,如果 type 包含 0 那么我想从 [= 中获取 name 列45=] table 其他来自 customer_old table。

为此,我在下面做了 mysql 查询:

SELECT email.*, 
CASE email.`type`
    WHEN 1 THEN customer_old.name
    ELSE customer_new.name
END AS customer_name 
LEFT JOIN 
CASE email.`type`
    WHEN 0 THEN customer_new ON email.customer_id = customer_new.id
    ELSE customer_old ON email.customer_id = customer_old.id
END
FROM email

现在当我 运行 这个查询 mysql 总是抛出错误。
有人可以解决我关于通过基于条件的 CASE 语句加入两个 table 的问题吗?

提前致谢。

试试下面的查询。

SELECT email . * , IF( email.type = '1', customer_old.name, customer_new.name ) AS name 
FROM email
LEFT JOIN customer_old ON ( customer_old.id = email.customer_id ) 
LEFT JOIN customer_new ON ( customer_new.id = email.customer_id )
select email.*,
CASE email.type 
  when 1 then customer_old.name
  else customer_new.name 
  end as filteredname
from email,customer_new,customer_old 
where 
  customer_new.id=email.id 
and 
  customer_old.id=email.id;

您可以使用左连接来优化执行。

另一种选择,

SELECT * FROM email 
LEFT JOIN customer_new AS customer ON email.customer_id = customer.id 
WHERE email.type = 0

UNION

SELECT * FROM email 
LEFT JOIN customer_old AS customer ON email.customer_id = customer.id 
WHERE email.type = 1