2016-11-09 2 views
1

Я ищу ускорение запроса (PostgreSql 9.5), но я не могу его изменить, потому что он выполняется приложением, которое я не могу изменить.Невозможно изменить запрос PostgreSql, как его ускорить

Таким образом, я захватил запрос из бревен PostGreSQL, здесь:

SELECT Count(*) 
FROM (SELECT ti.idturnosistemaexterno, 
       ti.historiaclinica_hp, 
       p.patientname, 
       CASE 
       WHEN (ti.creationdate :: VARCHAR IS NOT NULL) THEN 
       Date_trunc('SECOND', ti.creationdate) :: VARCHAR 
       ELSE 'NO EXISTE' :: VARCHAR 
       END AS creationdate, 
       CASE 
       WHEN (st.idstudy :: VARCHAR IS NOT NULL) THEN 'SI' :: VARCHAR 
       ELSE 'NO' :: VARCHAR 
       END AS idstudy, 
       st.institutionname, 
       CASE 
       WHEN (st.created_time :: VARCHAR IS NOT NULL) THEN 
       Date_trunc('SECOND', st.created_time) :: VARCHAR 
       ELSE 'NO EXISTE' :: VARCHAR 
       END AS created_time, 
       ti.enviado, 
       st.accessionnumber, 
       st.modality 
     FROM study st 
       right join turnointegracion ti 
         ON st.accessionnumber = ti.idturnosistemaexterno 
       left join patient p 
         ON st.idpatient = p.idpatient 
     ORDER BY ti.creationdate DESC) AS foo; 

объяснить анализ вывод заключается в следующем:

                 QUERY PLAN                  
-------------------------------------------------------------------------------------------------------------------------------------------------------- 
Aggregate (cost=231136.16..231136.17 rows=1 width=0) (actual time=32765.883..32765.883 rows=1 loops=1) 
    -> Sort (cost=230150.04..230314.39 rows=65741 width=8) (actual time=32754.992..32761.780 rows=64751 loops=1) 
     Sort Key: ti.creationdate DESC 
     Sort Method: external merge Disk: 1648kB 
     -> Hash Right Join (cost=219856.39..224889.28 rows=65741 width=8) (actual time=26653.007..32714.961 rows=64751 loops=1) 
       Hash Cond: ((st.accessionnumber)::text = (ti.idturnosistemaexterno)::text) 
       -> Seq Scan on study st (cost=0.00..4086.26 rows=77126 width=12) (actual time=12.983..6032.251 rows=77106 loops=1) 
       -> Hash (cost=219048.95..219048.95 rows=64595 width=16) (actual time=26639.722..26639.722 rows=64601 loops=1) 
        Buckets: 65536 Batches: 1 Memory Usage: 3602kB 
        -> Seq Scan on turnointegracion ti (cost=0.00..219048.95 rows=64595 width=16) (actual time=17.259..26611.806 rows=64601 loops=1) 
Planning time: 25.519 ms 
Execution time: 32766.710 ms 
(12 rows) 

Вот соответствующие определения таблицы:

Таблица "public.turnointegracion"

  Column   |   Type    |        Modifiers        
---------------------------+-----------------------------+-------------------------------------------------------------------- 
idturnosistemaexterno  | character varying(50)  | 
historiaclinica_hp  | integer      | 
matriculaprofrealiza  | character varying(10)  | 
matriculaprofinforma  | character varying(10)  | 
obrasocial    | character varying(20)  | 
planobrasocial   | character varying(20)  | 
nroafiliado    | character varying(20)  | 
nroautorizacion   | character varying(20)  | 
matriculaprofprescribe | character varying(10)  | 
codigonomenclador   | character varying(10)  | 
cantidadcodigonomenclador | integer      | 
importeunitariohonorarios | money      | 
importeunitarioderechos | money      | 
nrodefacturacion   | character varying(15)  | 
informe     | bytea      | 
titulodelestudio   | character varying(250)  | 
fechaprescripcion   | timestamp without time zone | 
fechahora     | timestamp without time zone | 
enviado     | boolean      | not null default false 
enviadofechahora   | timestamp without time zone | 
procesado_hp    | timestamp without time zone | 
modalidad     | character varying(6)  | 
orden      | integer      | not null default nextval('turnointegracion_orden_seq'::regclass) 
idturno     | integer      | not null default nextval('seq_turnointegracion_idturno'::regclass) 
creationdate    | timestamp without time zone | default now() 
informetxt    | text      | 
informedisponible   | timestamp without time zone | 
informeprocesado   | timestamp without time zone | 
Indexes: 
    "turnointegracion_pkey" PRIMARY KEY, btree (idturno) 
    "idx_fechahora" btree (fechahora) 
    "idx_historiaclinicahp" btree (historiaclinica_hp) 
    "idx_idturnosistemaexterno" btree (idturnosistemaexterno) 
    "idx_informedisponible" btree (informedisponible) 
    "idx_turnointegracion_creationdate" btree (creationdate DESC) 
    "idx_turnointegracion_idturnosistext_text" btree ((idturnosistemaexterno::text)) 

Таблица «public.study»

  Column   |   Type    |      Modifiers       
------------------------------+-----------------------------+--------------------------------------------------------- 
idstudy      | integer      | not null default nextval('study_idstudy_seq'::regclass) 
studydate     | date      | 
studytime     | time without time zone  | 
studyid      | character varying(20)  | 
studydescription    | character varying(255)  | 
modality      | character varying(2)  | 
modalityaetitle    | character varying(50)  | 
nameofphysiciansreadingstudy | character varying(255)  | 
accessionnumber    | character varying(20)  | 
performingphysiciansname  | character varying(255)  | 
referringphysiciansname  | character varying(255)  | 
studyinstanceuid    | character varying(255)  | 
status      | status_      | 
institutionname    | character varying(100)  | 
idpatient     | integer      | 
created_time     | timestamp without time zone | 
Indexes: 
    "study_pkey" PRIMARY KEY, btree (idstudy) 
    "study_studyinstanceuid_key" UNIQUE CONSTRAINT, btree (studyinstanceuid) 
    "idx_study_accession_text" btree ((accessionnumber::text)) 
    "idx_study_accessionnumber" btree (accessionnumber) 
    "idx_study_idstudy" btree (idstudy) 
Foreign-key constraints: 
    "study_idpatient_fkey" FOREIGN KEY (idpatient) REFERENCES patient(idpatient) 
Referenced by: 
    TABLE "series" CONSTRAINT "series_idstudy_fkey" FOREIGN KEY (idstudy) REFERENCES study(idstudy) 

Как вы можете видеть, я добавил индексы на пораженные столбцами, но планировщик продолжает делать последовательное сканирование. Есть ли способ улучшить это ?.

+0

Итак, вы можете изменить db, но не запрос? –

+0

Да, это старый исполняемый файл. Я не могу получить доступ к исходному коду. – leonardorame

+0

Вы можете вставить схему учебного стола? – McNets

ответ

2

Там нет WHERE состояния, из-за это соединение:

right join turnointegracion ti 
        ON st.accessionnumber = ti.idturnosistemaexterno 

вы читаете все записи из turnointegracion, добавив индекс для `CreationDate» вы можете ускорить функцию сортировки, но опять-таки все записи вернулся.

Фильтрация creationdate может уменьшить последнее время.

+0

Спасибо @mcNets, это правильный ответ. – leonardorame

+0

добро пожаловать. – McNets

Смежные вопросы