我有以下查询:
select *
from House h
join Users u
on h.ID_COORD = u.ID
join PA_USERS createdBy
on h.USR_N_ID_CREATION = createdBy.ID
join Contacts c
on h.ConID= c.ID
left join Price p
on h.PriD = p.ID
join Car c
on h.CID = c.ID
left join Person p
on c.PID = p.ID
left join Assistance a
on c.AID = a.ID
left join Travel t
on p.SER_N_ID = t.SER_N_ID
left join Travel at
on a.SER_N_ID = at.SER_N_ID
where h.LEA_N_ID = 9132
and t.lang = 'en'
and p.lang = 'en'
and at.lang = 'en'
但是由于at.lang ='en',查询没有返回任何数据。 我在Assistance和Person上都需要左连接,并且在Travel表上的两个表都需要左连接。关于如何执行此操作的任何想法。
答案 0 :(得分:3)
在WHERE
中放置子句而不处理LEFT JOIN
中的可空性将导致联接隐式变为INNER JOIN
。以下面的简单示例为例:
SELECT *
FROM TableA A
LEFT JOIN TableB B ON A.PID = B.FID
WHERE B.[name] = 'John';
这会导致LEFT JOIN
隐式成为INNER JOIN
,因为条款B.[name] = 'John'
必须对所有行为真(无论{ {1}}已返回)。
通常,解决方案是将需求放在TableB
子句中:
ON
因此,您的查询将变为:
SELECT *
FROM TableA A
LEFT JOIN TableB B ON A.PID = B.FID
AND B.Name = 'John';
请注意,由于您已经重用了别名,因此无论如何也无法解决您的查询。例如SELECT *
FROM House h
JOIN Users u ON h.ID_COORD = u.ID
JOIN PA_USERS createdBy ON h.USR_N_ID_CREATION = createdBy.ID
JOIN Contacts c ON h.ConID = c.ID
LEFT JOIN Price p ON h.PriD = p.ID
JOIN Car c ON h.CID = c.ID
LEFT JOIN Person p ON c.PID = p.ID
AND p.lang = 'en'
LEFT JOIN Assistance a ON c.AID = a.ID
LEFT JOIN Travel t ON p.SER_N_ID = t.SER_N_ID
AND t.lang = 'en'
LEFT JOIN Travel at ON a.SER_N_ID = at.SER_N_ID
AND at.lang = 'en'
WHERE h.LEA_N_ID = 9132;
和Person p
。我没有为您解决这些错误,因为我怀疑我们这里没有完整的查询(由于别名重用,您的问题中的那个查询永远不会运行)。
答案 1 :(得分:1)
外部联接的意思是:当没有匹配记录时,添加一个伪记录,将所有列设置为空。
因此,如果没有匹配的旅行记录,t.lang
将为空;不会是“ en”。
将条件移至ON
子句以使其起作用:
left join Travel t on p.SER_N_ID = t.SER_N_ID and t.lang = 'en'
等
答案 2 :(得分:1)
使用LEFT JOIN
时,ON
条件不等同于where条件,因为前者仍将为您提供行,而后者则不会。 >
在您的位置删除此内容
and at.lang = 'en'
并将其添加到LEFT JOIN的打开位置:
left join Travel at
on a.SER_N_ID = at.SER_N_ID
and at.lang = 'en'
答案 3 :(得分:1)
将AND at.lang = 'en'
从WHERE
子句移到LEFT JOIN
子句。放入WHERE
子句会将LEFT JOIN
更改为INNER JOIN
SELECT *
FROM
House h
JOIN
Users u ON h.ID_COORD = u.ID
JOIN
PA_USERS createdBy ON h.USR_N_ID_CREATION = createdBy.ID
JOIN
Contacts c ON h.ConID = c.ID
LEFT JOIN
Price p ON h.PriD = p.ID
JOIN
Car c ON h.CID = c.ID
LEFT JOIN
Person p ON c.PID = p.ID
LEFT JOIN
Assistance a ON c.AID = a.ID
LEFT JOIN
Travel t ON p.SER_N_ID = t.SER_N_ID
LEFT JOIN
Travel at ON a.SER_N_ID = at.SER_N_ID
AND at.lang = 'en'
WHERE
h.LEA_N_ID = 9132
AND t.lang = 'en'
AND p.lang = 'en'
;