我有三个名为customer的表,customer_contacts,customer_sites。
客户表:
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
结果我得到了什么:
但我只得到两行数据而不是全部。如果其他表中没有数据,我需要显示所有数据。请提出任何建议。
答案 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
子句的一部分。