Doug
Doug

Reputation: 869

MySQL: Filtering JOINed rows

Ok, say I have a join query like this:

SELECT users.*
FROM users
LEFT JOIN votes ON (users.id = votes.userid)
GROUP BY users.id
HAVING count(votes.id) >= 0
ORDER BY count(votes.id) LIMIT 0,30

Which gets rows from users, sorted by the number of rows in the votes table with which they have a relationship.

My question: What is the proper way to use a WHERE clause like WHERE votes.timestamp BETWEEN date_add(NOW(),INTERVAL -24 HOUR) AND NOW(), such that users are sorted only based on the number of rows created in the past 24 hours with which they have relationships?

This makes sense to be able to do, I'm just not really sure where to put it.

Upvotes: 0

Views: 63

Answers (1)

PinnyM
PinnyM

Reputation: 35541

Add it to the ON clause:

LEFT JOIN votes ON (users.id = votes.userid) AND (votes.timestamp BETWEEN date_add(NOW(),INTERVAL -24 HOUR) AND NOW())

If you put the condition in the WHERE clause, you'll potentially be eliminating the user completely, negating the purpose of the LEFT JOIN. The ON clause won't have this problem.

Upvotes: 1

Related Questions