我有一些作者拍摄的某个国家的视频。我需要按国家/地区分组并显示该国家/地区的最长视频时间及其作者姓名。我知道如何选择具有最长持续时间的视频,但我不知道如何添加作者姓名。
这是我的脚本,显示该国家/地区的最长持续时间的视频。我只需要添加作者。
SELECT country.country_id, max(video.duration)
FROM VIDEO
JOIN COUNTRY ON country.country_id = video.country_id
JOIN AUTHOR ON author.author_id = video.author_id
GROUP BY country.country_id
答案 0 :(得分:1)
我认为JOIN
country
与country
没有必要,因为您不希望除country_id
和video
的主键之外的任何属性都在video
中}。
一种解决方案是使用WHERE
和MAX
SELECT VIDEO.*, AUTHOR.name
FROM VIDEO v1
JOIN AUTHOR ON author.author_id = v1.author_id
WHERE video.duration = (
SELECT max(v2.duration)
FROM VIDEO v2
WHERE v2.country_id = v1.country_id)
中选择适当的行
GROUP BY
如果你想避免依赖子查询,那么你可以使用 SELECT VIDEO.*, AUTHOR.name
FROM VIDEO v1
JOIN AUTHOR ON author.author_id = v1.author_id
JOIN (
SELECT v.country_id, max(v.duration) maxduration
FROM VIDEO v
GROUP BY v.country_id
) t ON v1.country_id = t.country_id and t.maxduration = v1.duration
[java.lang.IllegalArgumentException: DocValuesField "name" is too large, must be <= 32766]
答案 1 :(得分:0)
有几种方法可以解决这个问题,但ROW_NUMBER是一种更简单的方法。
SELECT *
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY c.country_id ORDER BY v.duration) AS rn,
*
FROM VIDEO AS v
JOIN AUTHOR AS a ON a.author_id = v.author_id
) AS t
WHERE t.rn = 1