【问题标题】:How to optimize the SQL query to reduce the runtime?如何优化 SQL 查询以减少运行时间?
【发布时间】:2023-03-03 23:21:01
【问题描述】:

下面是我正在使用的表结构示例。该表几乎包含 2 亿条记录。

query_1 返回 col_1、col_2 和 col_3 的不同组合。然后遍历这些组合以执行另一个查询。

鉴于表很大,此执行的运行时间非常长。我正在寻求优化这一点。有人可以帮我优化吗?

query_1 = select distinct col_1, col_2, col_3 from my_table

query_2 = select count (distinct col_4) from my_table mt
          where mt.col_1 = {} and mt.col_2 = {} and mt.col_3 = {} and mt.col_4 > {}
combinations = #output_of_query_1, this contains nearly 200K rows

for val1, val2, val3 in combinations:
    # execute query_2
    # query_2 uses the the val1, val2, and val3 for to the my_table

col_1 col_2 col_3 col_4 ... col_n
a c e 1 ... .....
a c e 2 ... .....
a c f 3 ... .....
a d e 1 ... .....
a d e 2 ... .....
a d e 3 ... .....
a d e 1 ... .....
b c f 1 ... .....
b c e 1 ... .....
b c e 2 ... .....
b c e 3 ... .....

【问题讨论】:

  • 您的问题不清楚,并试图从游标/编程的角度解释 SQL 问题。相反,请在输出中添加示例输入数据,并说明如何从 A 点到达 B 点。
  • 您能否粘贴您的代码,以便我们更好地了解您要做什么?

标签: python sql query-optimization


【解决方案1】:

您描述的两个查询可以表示为一个聚合查询:

select col_1, col_2, col_3, count(distinct col_4)
from my_table mt
group by col_1, col_2, col_3;

在大多数数据库中,这将是运行查询的最快方式。然后,许多数据库可以使用(col_1, col_2, col_3, col_4) 上的索引进行聚合查询。

【讨论】:

    【解决方案2】:

    请记住,在 where 子句中使用的过滤器也会降低您的查询性能。例如,在搜索文本的开头使用通配符 (more here): ("like %test") 可能会带来麻烦,因为它会强制进行索引扫描,从而导致效率降低。除此之外,相关的子查询可能是一个问题(不知道它是否用于您的案例)。

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 2020-02-10
      • 1970-01-01
      • 2021-07-22
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多