问题
I have two tables one of it is LEAGUE, another is MATCH , in MATCH table there is a column as refLeague now I want to get total matches of week
For example
Id TotalMatches
-- ------------
1 12
2 0
3 6
If there is no match, I want to write 0 as table
SELECT l.Id ,COUNT(m.Id) as TotalMatches
FROM LEAGUE l
LEFT JOIN MATCH m ON l.Id = m.refLeauge
WHERE
m.MatchDate >= DATEADD(dd, DATEDIFF(dd, 1, GETDATE()) / 7 * 7 + 1, 0)
AND m.MatchDate < DATEADD(dd, DATEDIFF(dd, -6, GETDATE())/7 * 7 + 1, 0)
AND l.refSport = 1
GROUP BY l.Id
I wrote this query but it is not giving any result due to no rows in Match table, but it must be written 0
Example
Id TotalMatches
-- ------------
1 0
2 0
3 0
Where is my mistake?
回答1:
Move the right table filters to ON
condition
Non matching records will have NULL
values in m.MatchDate
which will be filtered by the condition in Where
clause . Implicitly it will be converted to INNER JOIN
. So the condition should be moved to ON
clause which tells what are the records to be joined with LEAGUE
instead of filtering the result
SELECT l.id,
Count(m.id) AS TotalMatches
FROM league l
LEFT JOIN match m
ON l.id = m.refleauge
AND m.matchdate >= Dateadd(dd, Datediff(dd, 1, Getdate()) / 7 * 7 + 1, 0)
AND m.matchdate < Dateadd(dd, Datediff(dd, -6, Getdate()) / 7 * 7 + 1, 0)
WHERE l.refsport = 1
GROUP BY l.id
回答2:
The where is breaking the left join
SELECT l.Id, COUNT(m.Id) as TotalMatches
FROM LEAGUE l
LEFT JOIN MATCH m
ON l.Id = m.refLeauge
and m.MatchDate >= dateadd(dd, datediff(dd, 1, getdate()) / 7 * 7 + 1,0)
AND m.MatchDate < dateadd(dd, datediff(dd,-6, getdate()) / 7 * 7 + 1,0)
where l.refSport=1
GROUP BY l.Id
/ 7 * 7 = 1
When I started this answer the other answer was not yet posted
来源:https://stackoverflow.com/questions/44862219/sql-server-null-table-join