Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two SQL Joins, Two Different Results

Tags:

sql

mysql

Hows is it possible for these two queries to be different. I mean the first query didn't include all the rows from my left table so I put the conditions within the join part.

Query 1

SELECT COUNT(*) as opens, hours.hour as point 
FROM hours 
LEFT OUTER JOIN tracking ON hours.hour = HOUR(FROM_UNIXTIME(tracking.open_date)) 
WHERE tracking.campaign_id = 83 
AND tracking.open_date < 1299538799 
AND tracking.open_date > 1299452401 
GROUP BY hours.hour

Query 2

SELECT COUNT(*) as opens, hours.hour as point 
FROM hours 
LEFT JOIN tracking ON hours.hour = HOUR(FROM_UNIXTIME(tracking.open_date)) 
AND tracking.campaign_id = 83 
AND tracking.open_date < 1299538799 
AND tracking.open_date > 1299452401 
GROUP BY hours.hour

The difference is that the first query gives me 18 rows where there are no rows between point 17 to 22. But when I run the second query, it shows the fully 24 rows but for rows between 17 and 22 it has a value of 1! I would of expected it to be 0 or NULL? If it really is 1 should it not have appeared in the first query?

How has this happened?

like image 359
Abs Avatar asked Feb 10 '26 15:02

Abs


1 Answers

the first JOIN is really an INNER JOIN, the outer joined table should not appear in the WHERE clause like you have in the top query, instead of COUNT(*), pick a column from the outer joined table

like image 83
SQLMenace Avatar answered Feb 12 '26 05:02

SQLMenace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!