MySQL -优化查询运行时

wydwbb8l  于 2023-02-15  发布在  Mysql
关注(0)|答案(1)|浏览(134)

我正在使用tpch database,并希望使用更快的运行时优化一个查询。
我尝试向查询添加索引和视图,但它们没有提高性能。有人能提供建议吗?谢谢。

    • 连接:**
conn = mysql.connect(host = 'relational.fit.cvut.cz', port = int(3306), user = 'guest', passwd = 'relational', db = 'tpch')
    • 查询:**
WITH customer_lifetime_value AS (
  SELECT
    c_custkey,
    c_name,
    c_address,
    c_nationkey,
    c_phone,
    c_acctbal,
    c_mktsegment,
    c_comment,
    SUM(o_totalprice) AS ltv
  FROM customer
  JOIN orders
    ON o_custkey = c_custkey
  GROUP BY 1, 2, 3, 4, 5, 6, 7, 8
)

SELECT
  r_name,
  MAX(ltv) AS best_customer_value
FROM region
JOIN nation
  ON n_regionkey = r_regionkey
JOIN customer_lifetime_value clv
  ON clv.c_nationkey = n_nationkey
GROUP BY 1;
db2dz4w8

db2dz4w81#

你能试试这个吗?它应该读更少的数据,并给予你相同的输出:

WITH customer_lifetime_value AS 
(
    SELECT o_custkey
          ,SUM(o_totalprice) AS ltv
    FROM orders 
    GROUP BY o_custkey
)
SELECT
  r_name,
  MAX(ltv) AS best_customer_value
FROM customer_lifetime_value
JOIN customer
    ON o_custkey = c_custkey
JOIN nation
    ON c_nationkey = n_nationkey
JOIN region
    ON n_regionkey = r_regionkey
GROUP BY r_name

如果正确,则可以创建简单索引:

  • 仅包括o_custkey和o_totalprice的在单表
  • 在仅包含c_custkey和c_nationkey的客户表上

相关问题