如何摆脱“where”中的嵌套选择条款?

发布于 2024-12-16 12:21:24 字数 449 浏览 2 评论 0原文

我的数据库中有一个表,其中保存某些应用程序的配置设置以及这些配置的版本:

app_id | config  | version
--------------------------
app1   | conf1v1 |   1
app2   | conf2v1 |   1
app1   | conf1v2 |   2

我需要获取每个应用程序的最新配置(具有最大版本号的配置)。我使用这样的查询:

select c.app_id, c.config, c.version
from config c       
where 
  c.version=(select max(c2.version) from config c2 where c2.app_id = c.app_id)

但它似乎效率低下。我想知道,有没有更有效的方法来完成这项任务?

I have a table in my DB that holds configuration settings for some apps along with versions of these configs:

app_id | config  | version
--------------------------
app1   | conf1v1 |   1
app2   | conf2v1 |   1
app1   | conf1v2 |   2

I need to get the latest configurations (the ones with greatest version numbers) for each application. I use a query like this:

select c.app_id, c.config, c.version
from config c       
where 
  c.version=(select max(c2.version) from config c2 where c2.app_id = c.app_id)

But it seems to be inefficient. I wonder, are there more efficient ways to do this task?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

天邊彩虹 2024-12-23 12:21:24

您可以使用分析函数。这至少会更有效率一点,因为它避免了两次击中桌子。

SELECT app_id, config, version
  FROM (SELECT app_id,
               config,
               version,
               row_number() over (partition by app_id order by version desc) rnk
          FROM config)
 WHERE rnk = 1

You can use an analytic function. That will be at least a bit more efficient since it avoids hitting the table twice.

SELECT app_id, config, version
  FROM (SELECT app_id,
               config,
               version,
               row_number() over (partition by app_id order by version desc) rnk
          FROM config)
 WHERE rnk = 1
善良天后 2024-12-23 12:21:24

将 CTE 与 ROW_NUMBER() 组合将允许对表进行一次解析(如果可用,则使用索引,以进一步减少读取)...

WITH
  reversioned_config
AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY app_id ORDER BY version DESC) as descending_version
  FROM
    config
)
SELECT
  app_id,
  config,
  version
FROM
  reversioned_config
WHERE
  descending_version = 1

Combining a CTE with ROW_NUMBER() will allow a single parse of the table (using an index if available, to further reduce reads)...

WITH
  reversioned_config
AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY app_id ORDER BY version DESC) as descending_version
  FROM
    config
)
SELECT
  app_id,
  config,
  version
FROM
  reversioned_config
WHERE
  descending_version = 1
往事随风而去 2024-12-23 12:21:24

怎么样

select app_id, config, MAX(version) version  from config 
group by app_id, config

What about

select app_id, config, MAX(version) version  from config 
group by app_id, config
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文