【问题标题】:Query to display top rated artist albums in MS Access查询以在 MS Access 中显示评分最高的艺术家专辑
【发布时间】:2020-01-08 14:50:46
【问题描述】:

我在音乐数据库中有两张桌子。 [Artists] 具有 PK 艺术家 ID艺术家名称[Albums]FK 艺术家 IDalbum_idalbum_namerating

我想select MAX(rating), album_nameGROUP BY [album].artist_id。 Access 会阻止我显示 album_name,因为它必须包含在 GROUP BY 函数中,而 artist_id 则不符合这一点。

我的查询:

SELECT albums.artist_id, MAX(albums.rating) 
FROM Albums 
GROUP BY albums.artist_id;

上面的查询为每个艺术家选择了排名靠前的专辑,但不包括专辑的名称。我还尝试JOINs 让 artist_name 显示,但没有成功。

您能告诉我如何选择必填字段吗? 编辑:我得到了这个查询:

    SELECT Album_name, rating, Artists.artist_name
    FROM Albums
    INNER JOIN Artists ON Albums.artist_id = Artists.Artist_id
    WHERE rating = (select MAX(rating) from Albums i 
    WHERE i.artist_id = albums.artist_id)

【问题讨论】:

    标签: sql ms-access select


    【解决方案1】:

    有很多方法可以实现这一点-


    使用连接子查询:

    一种可能的方法是在子查询上使用inner join,为每个artist_id 选择最大评分:

    select t1.*
    from albums t1 inner join
    (
        select t2.artist_id, max(t2.rating) as mr
        from albums t2
        group by t2.artist_id
    ) q 
    on t1.artist_id = q.artist_id and t1.rating = q.mr
    

    请注意,如果两个或多个专辑具有相同的评分,这将返回多条记录。


    使用相关子查询:

    另一种方法是使用相关子查询,该查询尝试选择评分高于当前记录的记录,并返回此类子查询不返回结果的记录(由where not exists 子句表示):

    select t1.*
    from albums t1 where not exists 
    (
        select 1 from albums t2 
        where 
        t1.artist_id = t2.artist_id and t1.rating < t2.rating
    )
    

    使用具有不相等连接条件的 LEFT JOIN

    最后,您还可以通过以下方式将不等连接条件与left join 一起使用,返回连接右侧没有符合连接条件的记录的记录:

    select t1.* 
    from 
        albums t1 left join albums t2 on 
        t1.artist_id = t2.artist_id and t1.rating < t2.rating
    where 
        t2.rating is null
    

    此示例只能在 SQL 视图中的 MS Access 中表示,因为 MS Access 查询设计器无法显示具有相同连接条件的连接(即一个字段等于另一个)。

    此示例在操作上与相关子查询类似,但选择是通过连接执行的,而不是在WHERE 子句中。

    【讨论】:

    • 这些是独特的答案和警钟,我需要开始跳出框框思考!考虑到我的数据库很小,我没有预见到使用上述查询会出现任何问题......但我会用它们进行试验。
    【解决方案2】:

    我相信这就是你要找的。​​p>

    SELECT albums.artist_id, albums.album_name, artists.artist_name, MAX(albums.rating) 
    FROM albums INNER JOIN artists ON albums.artist_id = artists.artist_id
    GROUP BY albums.artist_id, albums.album_name, artists.artist_name;
    

    【讨论】:

    • 谢谢!这解决了一个问题,但我的主要问题是无法显示专辑名称。
    • 糟糕,我看错了。我以为你需要艺术家的名字。更新它以包含专辑名称。
    • 这导致了我在使用 Access 时遇到的问题。当我在 GROUP BY 子句中包含专辑名称时,它会显示每张专辑的最大评分,而不是每个艺术家。编辑:我让它与另一个查询一起工作。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 2015-01-30
    • 1970-01-01
    • 2012-02-15
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多