MySQL LEFT JOIN不正确

时间:2017-06-19 11:57:44

标签: mysql join

请帮助别人。有一个问题select from few tables mysql。得到答案,阅读有关LEFT JOIN http://www.mysql.ru/docs/man/LEFT_JOIN_optimisation.html(俄语)的文档。所以我有一个有效的查询:

select con.connection_id, com.company_name, ctx.contact_name 
from connections as con 
left join companies as com
on con.company_id = com.company_id
left join contacts as ctx
on con.contact_id = ctx.contact_id
WHERE com.name=LIKE ('%qwer%')

这很好用。我有一个名为地址的新表,有两个字段(id和street)。在表公司中,有一个带有address_id的字段。创建一个新查询:

select con.connection_id, com.company_name, ctx.contact_name 
from addresses as add, connections as con 
left join companies as com
on con.company_id = com.company_id
left join contacts as ctx
on con.contact_id = ctx.contact_id
where add.id=com.Legal_address
AND com.name=LIKE ('%qwer%')

它说:

  

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在'add,Connections as con LEFT JOIN Companies as com on con.company_id = com.id LE'第1行附近使用正确的语法

我做错了什么?

3 个答案:

答案 0 :(得分:1)

你正在混合显式和隐式连接..所以你用逗号分隔表..删除它并使用显式连接

select 
    con.connection_id
    , com.company_name
    , ctx.contact_name 
from addresses as `add`
inner join connections as con on `add`.id=con.Legal_address
left join companies as com on con.company_id = com.company_id
left join contacts as ctx on con.contact_id = ctx.contact_id

答案 1 :(得分:1)

不考虑为什么它使任何意义从表中应用左连接的问题,这似乎会分解N:M关系,混合传统和显式连接语法非常混乱。

您的代码中的另一个WTF是没有明显的理由添加地址表 - 因为您实际上并未使用其中的属性。

您的代码失败的原因是' ADD'是MySQL中的保留字。你可以引用它,但是(再次忽略房间里的大象)可以使用一致的语法更好地重写查询:

select con.connection_id, com.company_name, ctx.contact_name 
from addresses as add, connections as con 
left join (SELECT company_name, company_id
   FROM companies AS c
   INNER JOIN addresses AS a
     ON c.legal_address=a.id) as com 
 on con.company_id = com.company_id
left join contacts as ctx on con.contact_id = ctx.contact_id
;

.....但是这里困惑的背景使人们无法确定这是否会产生你想要的结果。

答案 2 :(得分:0)

好像你想在这里使用另一个连接。尝试这样的事情:

select con.connection_id, com.company_name, ctx.contact_name
from addresses as add
left join companies as com on add.id = com.Legal_address
left join connections as con on con.company_id = com.company_id
left join contacts as ctx on con.contact_id = ctx.contact_id