CREATETABLE 销售 ( ID INT, 客户ID INT, 金额 DECIMAL, 销售日期 DATE ) PARTITIONBYRANGE (YEAR(销售日期)) ( PARTITION p2023 VALUES LESS THAN (2024), PARTITION p2024 VALUES LESS THAN (2025) );
SELECT a.id, a.name, SUM(b.amount) AS total_amount FROM accounts AS a JOIN transactions AS b ON a.id = b.account_id WHERE b.transaction_date BETWEEN'2023-01-01'AND'2023-12-31' GROUPBY a.id, a.name ORDERBY total_amount DESC;
SELECT id, transaction_date, amount, AVG(amount) OVER (ORDERBY transaction_date ROWSBETWEEN6 PRECEDING ANDCURRENTROW) AS rolling_avg FROM transactions;
案例分析
假设我们有一个名为sales的表,包含销售数据的信息。在没有优化的情况下,我们运行以下查询:
1 2 3 4 5 6 7 8 9 10 11 12
SELECT store_id, SUM(sales_amount) FROM sales WHERE sale_date >='2023-01-01' AND sale_date <'2024-01-01' GROUPBY store_id ORDERBY SUM(sales_amount) DESC;
优化方案
添加索引:在sale_date和store_id上添加索引,提高查询效率。
1 2
CREATE INDEX idx_sale_date ON sales(sale_date); CREATE INDEX idx_store_id ON sales(store_id);
避免全表扫描:确保查询条件能利用索引,必要时可以在where条件中加入其他过滤条件。
使用物化视图:如果该查询非常频繁,可以考虑创建一个物化视图以缓存结果。
1 2 3 4 5 6 7 8
CREATE MATERIALIZED VIEW store_sales AS SELECT store_id, SUM(sales_amount) AS total_sales FROM sales GROUPBY store_id;