Home > Database > Mysql Tutorial > Why are Rows Missing from my Left Join Result?

Why are Rows Missing from my Left Join Result?

Barbara Streisand
Release: 2025-01-04 09:33:35
Original
418 people have browsed it

Why are Rows Missing from my Left Join Result?

Left Join Discrepancy: Rows Omitted

In this query, the LEFT JOIN between tables #appSteps and #appProgress is malfunctioning, resulting in the exclusion of expected rows from the result set.

Query in Question:

select p.appId, s.stepId, s.section, p.start
from #appSteps s with (nolock)
left join #appProgress p on s.stepId = p.stepId
where s.section is not null
and p.appId = 101
Copy after login

Expected Result:

appId stepId section start
101 1 Section 1 2016-01-03 00:00:00.000
101 2 Section 2 2016-01-03 00:00:00.000
101 10 Section 3 NULL

Actual Result:

appId stepId section start
101 1 Section 1 2016-01-03 00:00:00.000
101 2 Section 2 2016-01-03 00:00:00.000

Resolution:

The erroneous behavior arises from including the right-hand table (#appProgress) in the WHERE clause. By moving this condition to the ON clause of the LEFT JOIN, the desired result can be achieved:

Select    P.appId, S.stepId, S.section, P.start
From      #appSteps    S   With (NoLock)
Left Join #appProgress P   On  S.stepId = P.stepId 
                           And P.appId = 101
Where     S.section Is Not Null
Copy after login

In a LEFT JOIN, the WHERE clause is executed after the join, meaning that rows from the right-hand table that don't meet the WHERE clause criteria will be excluded from the result set. Including the right-hand table in the WHERE clause effectively transforms it into an INNER JOIN, filtering out expected results.

The above is the detailed content of Why are Rows Missing from my Left Join Result?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template