admin

加入而不是相关子查询

sql

CREATE TABLE BlogPosts 
(
PostID INT PRIMARY KEY  not null,
PostTitle NVARCHAR ,
BlogID int,
TotalComments int
)

可以使用任何Join而不是相关子查询来简化此查询吗?

SELECT TOP 5 *
FROM BlogPosts as t0
WHERE t0.PostID = (SELECT TOP 1 t1.PostID 
                FROM BlogPosts as t1
                WHERE t0.BlogID = t1.BlogID
                ORDER BY t1.TotalComments DESC)

我需要来自不同博客的5个帖子,其maxTotalComments数量最多。

UPD。SQL Server,但我希望使用标准SQL


阅读 157

收藏
2021-07-01

共1个答案

admin

如果我正确理解,postid是唯一的,所以这应该有所帮助

编辑:

好,那就试试

DECLARE @BlogPosts  TABLE
( 
    PostID INT PRIMARY KEY  not null, 
    PostTitle NVARCHAR , 
    BlogID int, 
    TotalComments int 
)

INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 1, 'A', 1, 3
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 2, 'B', 1, 4
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 3, 'C', 2, 5
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 4, 'D', 2, 6
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 5, 'E', 2, 7
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 6, 'F', 1, 8
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 7, 'G', 3, 9
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 8, 'H', 4, 10
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 9, 'I', 5, 11
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 10, 'J', 6, 5

SELECT  TOP 5 *
FROM    @BlogPosts bp INNER JOIN
        (
            SELECT  BlogID,
                    MAX(TotalComments) MaxComments
            FROM    @BlogPosts
            GROUP BY BlogID
        ) maxCommentsPerBlog ON bp.BlogID = maxCommentsPerBlog.BlogID
                            AND bp.TotalComments = maxCommentsPerBlog.MaxComments
ORDER BY bp.TotalComments DESC

不过,您可能有多个max blog-totalComments组合。

2021-07-01