LEFT JOIN 3个表,其中某些字段丢失(NULL)

时间:2019-01-26 23:04:51

标签: mysql sql

我有一个包含3个表的数据库:公司,地址,联系方式,基本上包含有关公司本身的一些数据,分别是公司的地址和联系方式。现在,并非所有公司都有地址信息和联系信息。我正在尝试查询数据库以显示所有公司的列表:包括公司名称,地址和联系电话的表格。所以我使用这样的查询:

SELECT company.inn, company.name, company.ceo, address.city, contact.phone
    FROM company 
    JOIN address
    JOIN contact
    ON company.id = address.company_id AND company.id = contact.company_id

效果很好,但不会返回没有地址或联系方式或没有地址或联系方式的公司。因此,我然后尝试发出左连接命令:

SELECT company.inn, company.name, company.ceo, address.city, contact.phone
    FROM company 
    LEFT JOIN address
    LEFT JOIN contact
    ON company.id = address.company_id AND company.id = contact.company_id

我收到此错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

1 个答案:

答案 0 :(得分:3)

SELECT company.inn, company.name, company.ceo, address.city, contact.phone
FROM company 
LEFT JOIN address
ON company.id = address.company_id
LEFT JOIN contact 
ON company.id = contact.company_id

ON必须在JOIN之后定义。您可以在https://dev.mysql.com/doc/en/join.html

处阅读文档