MySQL SELECT Counter, Group By

前端 未结 2 1612
闹比i
闹比i 2021-01-21 04:02

im not sure if what I am asking for is possible... but it probably is lol.

Basically, I have two tables, tracks and albums.

I want to display a list of all track

相关标签:
2条回答
  • 2021-01-21 04:07

    We need to do something like ROW_NUMBER() OVER(Partition By AlbumTitle). Based on the trick defined in this article for Analytical functinons in MySQl.

    SELECT MO.*,
           @_rowNumber := @_rowNumber + 1
      FROM
           (
            SELECT m.*
              FROM
                   (
                    Select @_albumTitle := NULL
                   ) V,
                   (
                    SELECT tbl_tracks.title As TrackTitle, 
                           tbl_albums.title As AlbumTitle
                      FROM tbl_tracks, 
                           tbl_albums 
                     WHERE tbl_tracks.album_id = tbl_albums.id
                   ) m
             ORDER BY m.AlbumTitle,m.TrackTitle
           ) MO
     WHERE (CASE WHEN @_albumTitle IS NULL 
                   OR @_albumTitle <> MO.AlbumTitle THEN @_rowNumber := 0 END IS NOT NULL)
       AND (@_albumTitle := MO.AlbumTitle) IS NOT NULL
    

    NOTE: I have experience only in MS SQL, so this query may be wrong syntactically. And this query is Untested in MySql. I just read the code from article above and tried to follow the same approach.

    0 讨论(0)
  • 2021-01-21 04:27
    SELECT @rn := if(@g = tbl_albums.id, @rn+1, 1) rownumber,
           tbl_tracks.title, tbl_albums.title,
      @g := tbl_albums.id
    FROM (select @g:=null, @rn:=0) initvars
    CROSS JOIN tbl_tracks
    INNER JOIN tbl_albums on tbl_tracks.album_id = tbl_albums.id
    ORDER BY tbl_albums.id, tbl_tracks.title;
    
    0 讨论(0)
提交回复
热议问题