【问题标题】:SQL - Two columns group by issue with MAX functionSQL - 使用 MAX 函数按问题分组两列
【发布时间】:2018-11-08 01:13:35
【问题描述】:
SELECT artist.name, recording.name, MAX(recording.length)
FROM recording 
INNER JOIN (artist_credit 
            INNER JOIN (artist_credit_name 
                        INNER JOIN artist 
                                ON artist_credit_name.artist_credit=artist.id)
                    ON artist_credit_name.artist_credit=artist_credit.id)
        ON recording.artist_credit=artist_credit.id
WHERE artist.gender=1 
  AND recording.length <= (SELECT MAX(recording.length) FROM recording)
GROUP BY artist.name, recording.name
ORDER BY artist.name

我们在学校使用 MusicBrainz 数据库,但我们在使用“GROUP BY”时遇到了问题,因为我们有两列(它适用于一列,但不是两列)。我们希望结果只显示一位录制时间第二长的艺术家,但代码显示同一艺术家每首歌曲的所有录制时间。 有什么建议?谢谢。

【问题讨论】:

  • 为什么有嵌套连接?
  • 如果是 TSQL,我会使用窗口函数来为每个艺术家找到第二长的录音。网络搜索可能会揭示如何使用 Postgre 完成同样的任务。
  • @HaleemurAli 因为我们需要的数据来自不同的表。
  • 我看到了连接的必要性,但我认为不需要像您所做的那样嵌套它们。如果删除连接子句中的所有括号,则查询是等效的
  • @JoeC 我们已经在网上搜索了几个小时,只找到了带有单列的 group by。具有两列的唯一解决方案是使用 COUNT 函数,但我们不能使用它。

标签: sql database postgresql max aggregate-functions


【解决方案1】:

您无需仔细查看连接条件进行多次连接。它们可以减少到只有一个连接,如下所示。

SELECT DISTINCT B.name, A.name, A.length
FROM recording A JOIN artist B
ON A.artist_credit=B.id
WHERE B.gender=1
AND A.length=(SELECT C.length FROM recording C    
              WHERE C.artist_credit=B.artist_credit 
              ORDER BY C.length LIMIT 1, 1)
ORDER BY B.name;

Using MySQL LIMIT to get the nth highest value

【讨论】:

  • 我不得不使用多个连接,因为我有一个我应该遵循的 E/R 表(学校的东西)btw LIMIT #,# postgres 不支持
【解决方案2】:

正如其他人所指出的,可以减少连接语句。 AND语句中的运算符似乎也有问题;它应该是 What is the simplest SQL Query to find the second largest value?)。

我建议尝试以下方法:

SELECT artist.name, recording.name, MAX(recording.length)
FROM recording 
JOIN artist ON recording.artist_credit = artist.id
WHERE 
    artist.gender=1 
    AND 
    recording.length < (SELECT MAX(recording.length) FROM recording)
GROUP BY artist.name
ORDER BY artist.name

【讨论】:

  • 在 postgre 上尝试过,它给出了一个错误,因为recording.name 应该在 GROUP BY 上,如果我把它放在 GROUP BY 上,这与我的代码基本相同
  • 请为您的问题提供一些模型数据,以便我们更容易理解您的问题。
猜你喜欢
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 2012-02-19
  • 1970-01-01
  • 2020-12-26
  • 2011-06-20
相关资源
最近更新 更多