php - Mysql从具有外键关系的三个表中连接查询

标签 php mysql

我有三个表,分别称为 customers、customer_contacts、customer_sites。

客户表:

enter image description here

客户联系人:

enter image description here

客户网站:

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

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

最佳答案

将 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/

相关文章:

php - Beanstalkd 如何管理内存?

mysql - WHERE 子句中的别名

java - 从 MySQL 表获取 UUID(作为字符串),但打印输出为 "true"?

mysql - 我想在 mysql workbench 表中同一列的同一字段中有 2 个不同的值?

php - 使用内联 block 将文本对齐到 div 的底部

php - 如何从外部 View 在 Laravel blade @foreach 循环中获取变量

mysql - Perl - 如何将数据库中的 ' 解码或替换为单引号以供浏览器显示

MySQL:为什么我不能将多个值插入到我的表中?

php - dropzone 未上传,400 错误请求,token_not_provided

javascript - 选择或取消选择复选框