使用LEFT JOIN从多个表中进行选择

时间:2016-07-30 19:15:49

标签: mysql

我有3张桌子

t1 (select these records)
-------------
id
offer_id
business_id

t2 (offer details)
-------------
id
offer_details
business_id


t3 (business details)
-------------
id
business_name

我需要从t1中选择所有记录并从t2和t3添加信息。似乎基本但我似乎无法做到正确 - 必须是热量。

SELECT t2.offer_details, t3.business_name
FROM t2
LEFT JOIN t1 ON (t1.offer_id = t2.id)
LEFT JOIN t3 ON (t1.business_id = t3.id)

3 个答案:

答案 0 :(得分:1)

这个怎么样

Select t2.offer_details, t3.business_name
From t1
Left Join t2 ON (t1.offer_id = t2.id)
Left Join t3 ON (t1.business_id = t3.id)

答案 1 :(得分:1)

应该是

 SELECT t2.offer_details, t3.business_name
 FROM t1
 LEFT JOIN t1 ON (t1.offer_id = t2.id)
 LEFT JOIN t3 ON (t1.business_id = t3.id)

您的潜在客户表是t1,联接应该基于此表

答案 2 :(得分:1)

如果您想要来自t1的所有记录,请在您选择的部分添加t1.*。假设t1中的所有ID都存在于其他2个表中

SELECT
    t1.*, t2.offer_details, t3.business_name
FROM
    t1
    JOIN t2 ON t2.id = t1.offer_id
    JOIN t3 ON t3.id = t1.business_id

如果在t2或t3中缺少t1中的ID,则修改为LEFT JOIN