SQL Query Optimization for Faster Data Retrieval
This SQL query retrieves information from multiple tables, including t_dts_collect, t_patch_info, t_dts_details, and t_issue_track_summary_info. To optimize this query, we can implement the following strategies:
-
Indexing: Add indexes to frequently used columns such as
collect.patch_id,collect.dts_biz_no, anddetails.parent_no. Indexing helps the database quickly locate the required data, speeding up the query. -
Window Functions: Replace the subquery with window functions to improve performance. For instance, the
issuesubquery can be optimized as:
SELECT cmm_id,
string_agg(l3_flag, ';') OVER (PARTITION BY cmm_id) AS l3_flag,
string_agg(care_id, ';') OVER (PARTITION BY cmm_id) AS care_id,
string_agg(care_name, ';') OVER (PARTITION BY cmm_id) AS care_name,
string_agg(ump_id, ';') OVER (PARTITION BY cmm_id) AS issue_id
FROM t_issue_track_summary_info
WHERE deleted IS NULL
-
Join Order: Reorder joins to minimize the size of intermediate result sets. Consider placing the subquery as the last join to reduce data volume in earlier stages.
-
Avoid Functions: Avoid using functions in query conditions. For example, replace
collect.version_id = '23735486'with a direct string comparison for better efficiency.
Optimized Query:
SELECT collect.id,
CASE WHEN issue.l3_flag IS NULL THEN '' ELSE issue.l3_flag END AS L3flag,
issue.care_id,
CASE WHEN issue.care_name IS NULL THEN '' ELSE issue.care_name END AS CareName,
issue.issue_id,
collect.patch_plan,
collect.patch_id,
collect.cur_step,
collect.turns,
collect.cur_test,
...
FROM t_dts_collect collect
LEFT JOIN t_patch_info patch ON collect.patch_id = patch.id
LEFT JOIN t_dts_details details ON collect.dts_biz_no = details.dts_biz_no
LEFT JOIN t_dts_details details_parent ON details.parent_no = details_parent.dts_biz_no
LEFT JOIN (
SELECT cmm_id,
string_agg(l3_flag, ';') OVER (PARTITION BY cmm_id) AS l3_flag,
string_agg(care_id, ';') OVER (PARTITION BY cmm_id) AS care_id,
string_agg(care_name, ';') OVER (PARTITION BY cmm_id) AS care_name,
string_agg(ump_id, ';') OVER (PARTITION BY cmm_id) AS issue_id
FROM t_issue_track_summary_info
WHERE deleted IS NULL
) issue ON collect.dts_biz_no = issue.cmm_id
WHERE collect.is_deleted = 0
AND collect.version_id = '23735486'
AND collect.patch_plan IN ('CP2118')
ORDER BY details.create_time DESC
LIMIT 200
By implementing these optimization techniques, you can significantly improve the performance of your SQL queries and ensure faster data retrieval.
原文地址: https://www.cveoy.top/t/topic/qszY 著作权归作者所有。请勿转载和采集!