【问题标题】:SQL join with 2 tables - sort distinct result on column of second join带有 2 个表的 SQL 连接 - 在第二个连接的列上对不同的结果进行排序
【发布时间】:2018-08-30 18:28:40
【问题描述】:

抱歉标题不好,但我不知道如何更好地描述它。

我有 3 张桌子

1.) 竞赛

ID   Title
----------
1    Contest 1
2    Contest 2
3    Contest 3

2.) 竞赛系列

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需要不同。

【问题讨论】:

    标签: mysql sql join sql-order-by


    【解决方案1】:

    我认为这只是joingroup 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;
    

    【讨论】:

    • 首先感谢您编辑我的帖子以获得正确的布局。其次,谢谢你。我觉得我想的有点太复杂了……
    【解决方案2】:

    我稍微修改了一下,但@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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2022-12-22
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多