I am kind of stuck..
I have two tables
mysql > EXPLAIN event;
+-------------+--------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | MUL | | |
| extUrl | varchar(192) | NO | | | |
+-------------+--------------+------+-----+---------------------+-----------------------------+
One event can have many
mysql> explain eventDate;
+----------------+--------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| category_id | int(11) | NO | MUL | 0 | |
| event_id | int(11) | NO | MUL | 0 | |
| location_id | int(11) | NO | MUL | 0 | |
| name | varchar(100) | NO | | | |
| eventDate | timestamp | NO | | 0000-00-00 00:00:00 | |
+----------------+--------------+------+-----+---------------------+-----------------------------+
I’d like to query the event by id, with the location_id of the next upcoming eventDate and I am stuck how to form that query
I currently have this
SELECT
e.id,
d.location_id,
d.eventDate
FROM
event e
INNER JOIN eventDate d ON d.event_id = e.id AND d.eventDate >= CURRENT_TIMESTAMP
WHERE
e.id = 5107
GROUP BY
e.id
ORDER BY
d.eventDate ASC
Now this returns a result, but I GROUP BY event, so I am unsure how to ensure that really the next eventDate is selected. Also I didn’t use any aggregate function ( group by one, aggregate many ), which doesn’t seem to be a clean and clearly defined result requirement – MySQL is randomly selecting one of the eventDate rows now isn’t it?
This should always give you the first upcoming event:
But the better way is to add
LIMIT 1to your current query and removing theGROUP BY: