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.
这篇关于加入而不是相关子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:加入而不是相关子查询


基础教程推荐
猜你喜欢
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在多列上分布任意行 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01