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

时间:2015-05-30 07:25:10

标签: php mysql join left-join case

我有三个表:电子邮件 customer_new customers_old 。 现在,在电子邮件表中,有一个名为类型的字段,其中包含 0 1 。 因此,如果类型包含 0 ,那么我想从 customer_old 表中 customer_old <获取名称列/ strong>表。

为此我在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语句解决我关于加入两个表的问题吗?

提前致谢。

3 个答案:

答案 0 :(得分:3)

尝试以下查询。

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 )

答案 1 :(得分:0)

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;

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

答案 2 :(得分:0)

另一种选择,

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