我有一个查询,我没有直观地看到语法或格式错误。
但执行时,SSMS报告“值”附近存在语法错误。
select * from sw.Users u
join sw.Locations l
join sw.Organizations o
on u.LocationID = l.LocationID
and l.OrganizationID = o.OrganizationID
and o.OrganizationName = 'Value'
错误
Msg 102,Level 15,State 1,Line 38'Value'附近的语法不正确。
尝试以下结果:
select * from sw.Users u
join sw.Locations l
on u.LocationID = l.LocationID
为什么第一个连接查询报告错误?
答案 0 :(得分:3)
您的第一次加入错过了加入条件。 syntax为:a JOIN b ON ...
,而不仅仅是a JOIN b
。
如果您要加入三个表,则需要分两步完成,
(a JOIN b ON ...) JOIN c ON ...
或
a JOIN (b JOIN c ON ...) ON ...
请注意,括号是可选的,这可能是错误消息显示“near Value”的原因 - SQL Server假定您要使用第二种语法并错过了结尾处的第二个ON
言。
第一种语法通常更容易阅读。就个人而言,我会按如下方式编写SQL语句:
SELECT *
FROM sw.Users AS u
INNER JOIN sw.Locations AS l ON u.LocationID = l.LocationID
INNER JOIN sw.Organizations AS o ON l.OrganizationID = o.OrganizationID
WHERE o.OrganizationName = 'Value'
每个JOIN行添加另一个表,其ON子句描述旧结果集和新表之间的关系。实际的过滤条件在WHERE子句中。
答案 1 :(得分:0)
您需要在每次加入后添加“on”。
select * from sw.Users u
join sw.Locations l
on u.LocationID = l.LocationID
join sw.Organizations o
on l.OrganizationID = o.OrganizationID
where o.OrganizationName = 'Value'
有关详细信息,请查看here。
答案 2 :(得分:0)
每次(ON
)INNER
JOIN
个关键字
SELECT *
FROM sw.Users u
JOIN sw.Locations l ON u.LocationID = l.LocationID
JOIN sw.Organizations o ON l.OrganizationID = o.OrganizationID
AND o.OrganizationName = 'Value'
答案 3 :(得分:0)
尝试像这样重组
select * from sw.Users u
join sw.Locations l on u.LocationID = l.LocationID
join sw.Organizations o on
l.OrganizationID = o.OrganizationID
and o.OrganizationName = 'Value'