我有点卡住..
我有两张桌子
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 | | | |
+-------------+--------------+------+-----+---------------------+-----------------------------+
一个事件可以有很多
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 | |
+----------------+--------------+------+-----+---------------------+-----------------------------+
我想通过id
查询该事件,下一个即将发布<{strong> location_id
的{{1}},我不知道如何形成该查询
我目前有这个
eventDate
现在返回一个结果,但是我是GROUP BY事件,所以我不确定如何确保选择下一个eventDate。另外我没有使用任何聚合函数(逐个聚合,聚合很多),这似乎不是一个干净且明确定义的结果要求 - MySQL现在是随机选择一个eventDate行吗?
答案 0 :(得分:2)
这应该总能为您提供即将到来的第一个活动:
SELECT
e.id,
d.location_id,
d.eventDate
FROM
event e
INNER JOIN eventDate d ON d.event_id = e.id
WHERE
e.id = 5107
AND
d.id = (SELECT d1.id FROM eventDate d1 WHERE d1.event_id = 5107 AND d1.eventDate >= CURRENT_TIMESTAMP ORDER BY d1.eventDate ASC LIMIT 1)
但更好的方法是将LIMIT 1
添加到当前查询并删除GROUP BY
:
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
ORDER BY
d.eventDate ASC
LIMIT 1