I have a three table structure as follows (simplified):
users
-----
id
purchases
---------
id
user_id
events
------
id
purchase_id
starts_on (datetime)
I want to select all users who have an event that took place before some date in the past, but who do NOT have an event in the future. You can think of this as asking the question, "Which of my users were previously engaged with my company by attending events, but are not any longer?"
This query is being generated in Rails and I have cleaned it up to look as follows:
SELECT DISTINCT `users`.id FROM `users`
LEFT OUTER JOIN `events` ON events.user_id = users.id
LEFT OUTER JOIN `purchases` ON `purchases`.id = `events`.purchase_id
WHERE events.starts_on <= '2013-07-15' AND NOT events.starts_on >= '2013-08-12'
LIMIT 0, 30;
Although this query successfully retrieves users who have events prior to the first date parameter, it still includes users who have an event that starts in the future, which is not what I want. It appears that the "AND NOT" portion of my query is not working as expected.
I initially suspected that the problem was the use of a LEFT OUTER JOIN instead of an INNER JOIN, but changing this made no difference.
Help appreciated.