更快的选择最大 SQL 查询
Posted
技术标签:
【中文标题】更快的选择最大 SQL 查询【英文标题】:Faster select Max SQL Query 【发布时间】:2017-01-17 15:28:01 【问题描述】:这是用于选择具有最大行数的配置类型的查询。 是否有另一种与第二次查询一样快的方式来选择数据?
select CONFIG_TYPE, MAX(COUNTING) FROM
(select CONFIG_TYPE, COUNT(*) as COUNTING FROM NOTIFICATION_CONFIG GROUP BY CONFIG_TYPE)
WHERE COUNTING =
(select MAX(COUNTING) FROM
(select COUNT(*) as COUNTING FROM NOTIFICATION_CONFIG GROUP BY CONFIG_TYPE)
)GROUP BY CONFIG_TYPE
第二个查询将在 1 次搜索中完成这项工作,与另一个在 2 次搜索中完成的工作不同。
select CONFIG_TYPE, COUNTING FROM
(select CONFIG_TYPE, COUNT(*) as COUNTING FROM NOTIFICATION_CONFIG
GROUP BY CONFIG_TYPE ORDER BY COUNTING DESC FETCH FIRST 1 ROW ONLY)
只是想知道是否有其他方法可以做到这一点。
【问题讨论】:
我正在使用 IBM DB2 【参考方案1】:使用窗口函数!
SELECT c.*
FROM (SELECT CONFIG_TYPE, COUNT(*) as COUNTING,
RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
FROM NOTIFICATION_CONFIG
GROUP BY CONFIG_TYPE
) c
WHERE seqnum = 1;
这使用RANK()
,因此它将返回所有最大值(在平局的情况下)。如果您想在平局的情况下返回一个任意最大值,请改用ROW_NUMBER()
。或者,如果你不想打领带,你可以这样做:
SELECT CONFIG_TYPE, COUNT(*) as COUNTING
FROM NOTIFICATION_CONFIG
GROUP BY CONFIG_TYPE
ORDER BY COUNT(*) DESC
FETCH FIRST 1 ROW ONLY;
【讨论】:
【参考方案2】:这只是一团糟
select CONFIG_TYPE, MAX(COUNTING)
FROM ( select CONFIG_TYPE, COUNT(*) as COUNTING
FROM NOTIFICATION_CONFIG
GROUP BY CONFIG_TYPE
)
WHERE COUNTING = ( select MAX(COUNTING)
FROM ( select COUNT(*) as COUNTING
FROM NOTIFICATION_CONFIG
GROUP BY CONFIG_TYPE
)
)
GROUP BY CONFIG_TYPE
【讨论】:
以上是关于更快的选择最大 SQL 查询的主要内容,如果未能解决你的问题,请参考以下文章
SQL SERVER,使用(TABLOCKX)选择查询会比使用(NOLOCK)更快,反之亦然?