I’m looking to only return one day — so if there were 2 events on the same day, it will only return one of the events. Which event is chosen is arbitrary. The query which I thought would work is:
SELECT DISTINCT day(events.event_start_date),events.event_id
FROM scheduled_events
JOIN events ON (
scheduled_events.event_id = events.event_id
)
WHERE scheduled_events.user_id = 123
AND MONTH( events.event_start_date ) = 06
AND YEAR( events.event_start_date ) = 2012
Table: events
+------------+--------------------+
| event_id | event_start_date |
+------------+--------------------+
| 1 | 2012-06-06 |
| 2 | 2012-06-06 |
| 3 | 2012-06-07 |
+------------|--------------------|
Table: scheduled_events
+------------+-----------+
| event_id | user_id |
+------------+-----------+
| 1 | 123 |
| 2 | 123 |
| 3 | 123 |
+------------|-----------|
I would want the query to return events with id 3 and (1 or 2).
The
DISTINCTkeyword as you used it refers to whole rows, i.e. all your columns. For this reason you get multiple results per day. To only give a single result per day, you shouldGROUP BYthat value.This will work in mysql, and the listed event will be an arbitrary one, as you requested. But some other SQL dialects will forbid this, and even with mysql there might be cases where you want reproducible behaviour. In those cases, you should use an aggregate function with the
event_idas well, e.g.MIN(event_id).