如何摆脱“where”中的嵌套选择条款?
我的数据库中有一个表,其中保存某些应用程序的配置设置以及这些配置的版本:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用分析函数。这至少会更有效率一点,因为它避免了两次击中桌子。
You can use an analytic function. That will be at least a bit more efficient since it avoids hitting the table twice.
将 CTE 与 ROW_NUMBER() 组合将允许对表进行一次解析(如果可用,则使用索引,以进一步减少读取)...
Combining a CTE with ROW_NUMBER() will allow a single parse of the table (using an index if available, to further reduce reads)...
怎么样
What about