SQL 连接 2 个表 - 在第二个连接的列上对不同的结果进行排序
SQL join with 2 tables - sort distinct result on column of second join
抱歉标题不好,但我不知道如何更好地描述它。
我有3张桌子
1.) 比赛
ID Title
----------
1 Contest 1
2 Contest 2
3 Contest 3
2.) contest_series
ID contest_id series_id
----------------------------
1 1 3
2 1 2
3 2 1
4 2 2
5 3 3
3.)系列
ID start_date
----------------
1 2018-03-21 14:00:00
2 2018-03-21 15:00:00
3 2018-03-21 16:00:00
现在我要实现的是,获取按比赛中第一个开始系列的 start_date 排序的比赛列表。
想要的结果:
contest_id start_date_of_first_series
------------------------
2 2018-03-21 14:00:00
1 2018-03-21 15:00:00
3 2018-03-21 16:00:00
重要提示:结果中的 contest_id 需要不同。
我认为这只是 join
和 group by
:
select cs.contest_id, min(s.start_date) as first_start_date
from contest_series cs join
series s
on cs.series_id = s.series_id
group by cs.contest_id
order by first_start_date;
我稍微修改了一下,但@Gordon Linoff 引导我朝着正确的方向解决了我的问题:
select contests.* from contests
join (
select contest_series.contest_id, min(series.start) as first_start_date
from contest_series
join series on contest_series.series_id = series.id
group by contest_series.contest_id
) filtered_contests on filtered_contests.contest_id = contests.id
order by first_start_date
抱歉标题不好,但我不知道如何更好地描述它。
我有3张桌子
1.) 比赛
ID Title
----------
1 Contest 1
2 Contest 2
3 Contest 3
2.) contest_series
ID contest_id series_id
----------------------------
1 1 3
2 1 2
3 2 1
4 2 2
5 3 3
3.)系列
ID start_date
----------------
1 2018-03-21 14:00:00
2 2018-03-21 15:00:00
3 2018-03-21 16:00:00
现在我要实现的是,获取按比赛中第一个开始系列的 start_date 排序的比赛列表。
想要的结果:
contest_id start_date_of_first_series
------------------------
2 2018-03-21 14:00:00
1 2018-03-21 15:00:00
3 2018-03-21 16:00:00
重要提示:结果中的 contest_id 需要不同。
我认为这只是 join
和 group by
:
select cs.contest_id, min(s.start_date) as first_start_date
from contest_series cs join
series s
on cs.series_id = s.series_id
group by cs.contest_id
order by first_start_date;
我稍微修改了一下,但@Gordon Linoff 引导我朝着正确的方向解决了我的问题:
select contests.* from contests
join (
select contest_series.contest_id, min(series.start) as first_start_date
from contest_series
join series on contest_series.series_id = series.id
group by contest_series.contest_id
) filtered_contests on filtered_contests.contest_id = contests.id
order by first_start_date