有一个效率太低的Postgres查询。希望有人能指出我正确的方向,使这个查询合理运行。我知道总和是问题,而不是如何改进/修复它。
/* All Study Transfer Times */
WITH cte_images_duration AS
(
SELECT
ssi.study_id,
min(ssi.created_dt) AS first_image_created_dt,
--max(ssi.created_dt) AS last_image_created_dt,
max(ssi.created_dt) - min(ssi.created_dt) AS images_recieve_duration,
--count(ssi.study_id) AS image_count,
sum( cast(btrim(ssif.file_size, 'KB') as real) ) as transferSize
FROM study_series_instances AS ssi, study_series_instance_files as ssif
where ssi.created_dt >= '2017-1-6'
GROUP BY ssi.study_id
)
SELECT
s.institution AS "Institution",
s.accession_no AS "Accession#",
s.modalities,
to_char(timezone(f.time_zone, cte1.first_image_created_dt), 'MM/DD/YYYY HH:MI:SS pm') AS "Transfer Start Date/Time",
--to_char(timezone(f.time_zone, cte1.last_image_created_dt), 'MM/DD/YYYY HH:MI:SS pm') AS "Transfer Stop Date/Time",
to_char(cte1.images_recieve_duration, 'MI:SS') AS "Transfer Time",
--cte1.image_count AS "Image Count",
cte1.transferSize,
to_char(timezone(f.time_zone, s.study_unread_dt), 'MM/DD/YYYY HH:MI:SS pm') AS "Unread Date/Time"
--to_char(timezone(f.time_zone, s.approved_dt), 'MM/DD/YYYY HH:MI:SS pm') AS "Approved Date/Time"
FROM
cte_images_duration AS cte1
INNER JOIN studies AS s on s.id = cte1.study_id
INNER JOIN facilities f ON f.id = s.facility_id
where s.study_unread_dt > '2017-1-6'
ORDER BY s.accession_no
limit 10
答案 0 :(得分:2)
您可能在加入study_series_instances和study_series_instance_files时错过了一个条件。像:
FROM study_series_instances AS ssi
JOIN study_series_instance_files as ssif ON ssif.some_field = ssi.some_field
答案 1 :(得分:2)
除了@Dmitry和@a_horse_with_no_name注意事项外,我也会尝试这种方式:
SELECT
s.institution AS "Institution",
s.accession_no AS "Accession#",
s.modalities,
to_char(timezone(f.time_zone, cte1.first_image_created_dt), 'MM/DD/YYYY HH:MI:SS pm') AS "Transfer Start Date/Time",
to_char(cte1.images_recieve_duration, 'MI:SS') AS "Transfer Time",
cte1.transferSize,
to_char(timezone(f.time_zone, s.study_unread_dt), 'MM/DD/YYYY HH:MI:SS pm') AS "Unread Date/Time"
FROM
(SELECT
ssi.study_id,
min(ssi.created_dt) AS first_image_created_dt,
max(ssi.created_dt) - min(ssi.created_dt) AS images_recieve_duration,
sum(cast(btrim(ssif.file_size, 'KB') as real)) AS transferSize
FROM
study_series_instances AS ssi,
/* Some JOIN condition is expected here */
study_series_instance_files AS ssif
WHERE ssi.created_dt >= '2017-1-6'
GROUP BY ssi.study_id
) AS cte1
INNER JOIN studies AS s on s.id = cte1.study_id
INNER JOIN facilities f ON f.id = s.facility_id
WHERE s.study_unread_dt > '2017-1-6'
ORDER BY s.accession_no
LIMIT 10
PostgreSQL中的CTE表达式是optimization fences,有时候这不是你想要的。