简体   繁体   中英

MYSQL LIMIT on COUNT of DISTINCT row

Is there a way to set a LIMIT equal to the COUNT of DISTINCT entries in a row? I have below query and it all work but the LIMIT . My table will have a varying ammount of DISTINCT seriesID and I want the last Episode of the Last Season in each Distinct seriesID.

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 ???

I tried doing a sub query like below but that errors out.

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

This query may return the result you specified. The inline view t2 returns the maximum Season for each Series. The inline view t3 returns the maximum Episode for each Season of each Series. The results from the inline views (derived tables) can be joined to the original table, to retrieve the detail row associated with those maximum values. (This assumes that the (Series,Season,Episode) tuple is unique.)

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

EDIT

--or--

An equivalent result can be returned with a query like this. Inline view t2 returns the latest Episode of the latest Season for each Series.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM