我有三个表,分别称为 customers、customer_contacts、customer_sites。
客户表:
客户联系人:
客户网站:
如果其他两个表中没有相关数据,我希望显示客户数据。但是我的查询没有得到结果。 以下是查询:
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
我得到的结果:
但我只得到两行数据,而不是全部。如果其他表中没有数据,我需要显示所有数据。请提出任何建议。
最佳答案
将 where 添加到您的 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
如果您不这样做,您的左连接
将是一个内部连接
。
您也不能在 select 子句中使用列,它们不在聚合函数中,也不属于 Group by
子句的一部分。
关于php - Mysql从具有外键关系的三个表中连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44049975/