DISTINCT行的COUNT上的MYSQL LIMIT

时间:2015-05-29 01:31:07

标签: mysql subquery limit

有没有办法将LIMIT设置为等于COUNTDISTINCT条目?我有以下查询,但它只能LIMIT。我的表格会有DISTINCT个系列ID的变化,我希望每个Distinct系列ID中最后一集的最后一集。

SELECT t1.* FROM myTable.SeriesEpisodes t1 JOIN (SELECT seriesID, MAX(Season) Season FROM myTable.SeriesEpisodes GROUP BY seriesID) t2 ON t1.Season = t2.Season AND t1.seriesID = t2.seriesID ORDER BY Episode DESC LIMIT ???

我尝试过像下面这样的子查询,但是出错了。

LIMIT (SELECT COUNT(DISTINCT seriesID) FROM myTable.SeriesEpisodes)

1 个答案:

答案 0 :(得分:1)

此查询可能会返回您指定的结果。内联视图t2返回每个系列的最大季节。内联视图t3返回每个系列的每个季节的最大剧集。内联视图(派生表)的结果可以连接到原始表,以检索与这些最大值关联的详细信息行。 (这假设(Series,Season,Episode)元组是唯一的。)

SELECT t1.*
  FROM myTable.SeriesEpisodes t1
  JOIN ( SELECT s2.Series
              , MAX(s2.Season) AS Season
           FROM myTable.SeriesEpisodes s2
          GROUP
             BY s2.Series
       ) t2
    ON t2.Series  = t1.Series
   AND t2.Season  = t1.Season
  JOIN ( SELECT s3.Series
              , s3.Season
              , MAX(s3.Episode) AS Episode
           FROM myTable.SeriesEpisodes s3
          GROUP
             BY s3.Series
              , s3.Season
       ) t3
    ON t3.Series  = t1.Series
   AND t3.Season  = t1.Season
   AND t3.Episode = t1.Episode
 ORDER 
    BY t1.Series
     , t1.Season

修改

- 或 -

可以使用这样的查询返回等效结果。内联视图t2返回每个系列的最新季节的最新剧集。

SELECT t1.*
  FROM myTable.SeriesEpisodes t1
  JOIN ( SELECT s2.Series
              , s2.Season
              , MAX(s2.Episode) AS Episode
           FROM myTable.SeriesEpisodes s2
           JOIN ( SELECT s3.Series
                       , MAX(s3.Season) AS Season
                    FROM myTable.SeriesEpisodes s3
                   GROUP
                      BY s3.Series
                ) t3
             ON t3.Series  = s2.Series
            AND t3.Season  = s2.Season
          GROUP
             BY s2.Series
              , s2.Season
       ) t2
    ON t2.Series  = t1.Series
   AND t2.Season  = t1.Season
   AND t2.Episode = t1.Episode
 ORDER 
    BY t1.Series
     , t1.Season