加入而不是相关子查询

编程入门 行业动态 更新时间:2024-10-28 08:28:45
本文介绍了加入而不是相关子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
CREATE TABLE BlogPosts 
(
PostID INT PRIMARY KEY  not null,
PostTitle NVARCHAR ,
BlogID int,
TotalComments int
)

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

May this query be simplified with any Join instead of correlated subquery?

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 篇文章的总评论数上限.

I need 5 posts with max TotalComments from different blogs.

更新.SQL Server,但我更喜欢标准 SQL

UPD. SQL Server, but I would prefer standard SQL

推荐答案

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

If i understand correctly, postid is unique, so this should help

好的试试这个然后

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

不过,您可能有多个最大 blog-totalComments 组合.

You might have multiple max blog-totalComments combinations though.

这篇关于加入而不是相关子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 19:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1194834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!