Mysql连接查询三个具有外键关系的表

时间:2017-05-18 14:03:23

标签: php mysql

我有三个名为customer的表,customer_contacts,customer_sites。

客户表:

enter image description here

Customer_contacts:

enter image description here

Customer_sites:

enter image description here

如果其他两个表中没有相关数据,我希望显示客户数据。但是我的查询得不到结果。 以下是查询:

SELECT c.id,c.customer_code,c.customer_name,count(cs.customer_id) as count, cc.name,cc.email,cc.phone
from customers as c
left join customer_sites as cs on cs.customer_id = c.id
left join customer_contacts as cc on cc.customer_id = c.id
where cc.is_main =1 group by cc.id 

结果我得到了什么:

enter image description here

但我只得到两行数据而不是全部。如果其他表中没有数据,我需要显示所有数据。请提出任何建议。

1 个答案:

答案 0 :(得分:1)

添加你的on子句的位置:

SELECT c.id,c.customer_code,c.customer_name,count(cs.customer_id) as count, cc.name,cc.email,cc.phone
from customers as c
left join customer_sites as cs on cs.customer_id = c.id
left join customer_contacts as cc on cc.customer_id = c.id and cc.is_main =1
 group by cc.id 

如果您不这样做,left join将是inner join

你也不能在select子句中使用列,这些列不在Aggregate函数中,也不是Group by子句的一部分。