MYSQL子查询使用order by和group by

时间:2014-02-06 18:28:22

标签: mysql sql

我有四个联赛和赛季......

季节有league_id, start_date

我正试图抓住每个联赛的最新赛季......然后在赛季的开始日期按照asc顺序排列结果。

SELECT *
FROM leagues
JOIN (
  SELECT id as season_id, title as season_title, league_id, start_date
  FROM seasons
  ORDER BY start_date DESC) AS seasons
  ON leagues.id = seasons.league_id
ORDER BY seasons.start_date ASC;

我已经在这方面工作了一段时间......这种作品虽然可以为一个联赛夺得多个赛季记录......

我找到了一个使用PHP的解决方案,但我希望只使用MYSQL。

感谢任何建议。

4 个答案:

答案 0 :(得分:3)

您需要在子查询中使用MAX()聚合来获取每季最新的start_date,然后将其加入seasons表。

SELECT 
  /* Don't SELECT * in production code - 
     trim this to just the columns you actually need */
  leagues.*,
  seasons.*
FROM 
  /* Start with an inner join between seasons and leagues */
  leagues
  INNER JOIN seasons ON leagues.id = seasons.league_id
  INNER JOIN (
    /* Subquery gets leage_id and latest start date per league_id group */
    SELECT
      league_id,
      MAX(start_date) AS maxstart
    FROM seasons
    GROUP BY league_id
    /* joining back to seasons on both of those columns to return 
       the full season column data */
  ) maxseason 
    ON seasons.league_id = maxseason.league_id
       AND seasons.start_date = maxseason.startdate
ORDER BY seasons.start_date ASC

答案 1 :(得分:2)

您可以非常简单地使用自联接来执行此操作:

SELECT s1.*, l.*
FROM seasons s1
LEFT JOIN seasons s2
  ON s2.league_id = s1.league_id AND s2.start_date > s1.start_date
JOIN leagues l
  ON l.id = s1.league_id
WHERE s2.league_id IS NULL
ORDER BY s1.start_date

此方法通常优于子查询。

答案 2 :(得分:0)

您也可以使用group by:

SELECT *
FROM seasons s1
JOIN
    (SELECT l.id as league_id, s.id as season_id, MAX(start_date) as max_start_date
    FROM leagues l
    JOIN seasons s ON l.id = s.league_id
    GROUP BY l.id, s.id) ls ON (ls.season_id = s1.id AND s1.start_date = ls.max_start_date)
ORDER BY s1.start_date ASC

答案 3 :(得分:0)

mysql> select * from league;
+------+-----------------+
| id   | name            |
+------+-----------------+
|    1 | english premier |
|    2 | spanish premier |
|    3 | italian premier |
+------+-----------------+
3 rows in set (0.00 sec)

mysql> select * from season;
+------+-----------+------------+
| id   | league_id | startdate  |
+------+-----------+------------+
|    1 |         1 | 2013-04-01 |
|    2 |         2 | 2013-07-01 |
|    3 |         3 | 2013-12-01 |
|    3 |         2 | 2013-08-01 |
|    4 |         1 | 2014-01-01 |
|    5 |         3 | 2014-01-01 |
|    6 |         3 | 2015-01-01 |
+------+-----------+------------+
7 rows in set (0.00 sec)

mysql> select max(startdate), name from league l, season s where s.league_id=l.i
d group by league_id order by max(startdate);
+----------------+-----------------+
| max(startdate) | name            |
+----------------+-----------------+
| 2013-08-01     | spanish premier |
| 2014-01-01     | english premier |
| 2015-01-01     | italian premier |
+----------------+-----------------+
3 rows in set (0.00 sec)

我希望我的问题是对的。