Join instead of correlated subquery(加入而不是相关子查询)
本文介绍了加入而不是相关子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
这篇关于加入而不是相关子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:加入而不是相关子查询
基础教程推荐
猜你喜欢
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01