mysql:获取具有最大列值的别名的元组

时间:2015-03-03 04:09:52

标签: mysql sql max alias

我想做的是:

select AlbumId from (
    select Album.AlbumId, Sum(Track.UnitPrice) as Total from Album 
    inner join Track on Album.AlbumId = Track.AlbumId
    group by Album.AlbumId
) tpt 
where Total = (select max(Total) from tpt);

但我得到了:

  

表' db.tpt'不存在

- 这可能是有道理的。但是,我是SQL的新手,并且不知道为什么tpt超出了我的where子句的范围。我怎样才能做到这一点?我希望得到Max total的元组并提取AlbumId

谢谢!

1 个答案:

答案 0 :(得分:0)

使用带有子查询的JOIN

select tpt.AlbumId from (
    select Album.AlbumId, Sum(Track.UnitPrice) as Total from Album 
    inner join Track on Album.AlbumId = Track.AlbumId
    group by Album.AlbumId
) tpt 
JOIN (
    select Sum(Track.UnitPrice) as Total from Album 
    inner join Track on Album.AlbumId = Track.AlbumId
    group by Album.AlbumId
    ORDER BY Total DESC
    LIMIT 1
) maxtpt ON tpt.Total = maxtpt.Total