我遇到了需要一些“复杂”排序的Mysql查询。 我有两张桌子:
Training
+--------------+------------------+
| training_id | training_name |
+--------------+------------------+
| 1 | test1 |
| 2 | test2 |
| 3 | test3 |
+--------------+------------------+
Training_venue
+----------+--------------+------------+
| venue_id | training_id | venue_date |
+----------+--------------+------------+
| 1 | 2 | 2009-06-01 |
| 2 | 2 | 2012-06-01 |
| 3 | 2 | 2011-06-01 |
| 4 | 1 | 2009-09-01 |
| 5 | 1 | 2011-09-01 |
| 6 | 1 | 2012-09-01 |
| 7 | 3 | 2009-01-01 |
+----------+--------------+------------+
我期待以下结果:
+--------------+------------------+------------+--------------+
| training_id | training_name | venue_id | venue_date |
+--------------+------------------+------------+--------------+
| 2 | test2 | 2 | 2011-06-01 |
| 2 | test2 | 3 | 2012-06-01 |
| 1 | test1 | 6 | 2011-09-01 |
| 1 | test1 | 5 | 2012-09-01 |
+--------------+------------------+------------+--------------+
如您所见,结果要求是:
什么mysql查询将返回该结果集?
编辑: 这是我到目前为止所尝试的内容:
SELECT *
FROM `training` AS t
LEFT JOIN `training_venue` AS v USING ( `training_id` )
WHERE `venue_date` >= NOW()
ORDER BY `training_id;
但是,如果training_id的订单负责将所有培训“分组”在一起,则不允许从最快的场地培训到最近场地的培训。
我还编辑了数据表,以说明存在问题。看看结果是如何排序的,不是通过training_id,而是通过最快的场地。
编辑: 更正了日期。
答案 0 :(得分:2)
SELECT t1.training_id, t1.training_name, t2.venue_id, t2.venue_date
FROM Training t1
INNER JOIN Training_venue t2 ON t1.training_id = t2.training_id
WHERE t2.venue_date >= NOW()
ORDER BY t1.training_id ASC, t2.venue_date ASC
我不知道你的最后一点是什么:“在训练中,场地是从最快到最晚的。”但上述查询似乎符合您的其他需求。
编辑:我现在更了解你的目标。我认为这有点复杂。我会考虑另一个。 编辑:我想我拥有它!SELECT t1.training_id, t1.training_name, t2.venue_id, t2.venue_date
FROM Training t1
INNER JOIN (SELECT training_id, venue_date
FROM training_venue
WHERE venue_date >= NOW()
GROUP BY training_id
ORDER BY MIN(venue_date)) t3 ON t1.training_id = t3.training_id
INNER JOIN Training_venue t2 ON t1.training_id = t2.training_id
WHERE t2.venue_date >= NOW()
ORDER BY t3.venue_date DESC, t2.venue_date ASC
试试吧!
编辑:使用'2010-01-01'代替NOW()
因为NOW()
会丢失您似乎想要包含的2010日期。