2015-11-10 115 views
0

我有一系列需要運行的查詢。他們是單調的,幾乎所有人都使用相同的外鍵(trial_id)。有沒有辦法將所有這些單個查詢轉換爲一個查詢,以便發佈我需要的所有結果?優化Postgres計數(*)查詢

select count(*) as totalstudies from study; 
select count(*) as deletedstudies from study where trial_id = (select id from trial where name = 'abc'); 

select count(*) as portalemaillog from portalemaillog; 
select count(*) as deletedemaillog from portalemaillog where trial_id = (select id from trial where name = 'abc'); 

select count(*) as totalsites from trialsite; 
select count(*) as deletedsites from trialsite where trial_id = (select id from trial where name = 'abc'); 

select count(*) as totalsubjects from trialsubject; 
select count(*) as deletedsubjects from trialsubject where trial_id = (select id from trial where name = 'abc'); 

select count(*) as totaltimepointcount from timepoint; 
select count(*) as deletedtimepointcount from timepoint where id = (select id from trialversion where id = (select id from trial where name = 'abc')); 
+0

我不知道你的模式,但JOIN可能會比那些子查詢更好地執行,並且讀起來也更直觀。關於您的原始問題,您可以將每個子查詢合併爲一個子查詢,爲每個子查詢定義一個輸出字段。 – Eggplant

+0

你可能提供一個關於使用count(*)聚合的join語句的例子嗎?我之前完成了連接,但並未完全確定如何在此實例中使用它。 – ryekayo

+1

您將在連接上使用聚合函數,就像它是單個表一樣,如下所示:'SELECT COUNT(*)AS deletedstudies FROM study AS s INNER JOIN trial AS t ON s.trial_id = t.id WHERE t.name ='abc';' – Eggplant

回答

1

對於前四(因爲它們是類似的),你可以寫類似:

with trial as (select id from trial where name = 'abc') 
select count(t.id) as totalcount, count(trial.id) as subcount, name from (
    select id, trial_id, 'studies' as name from studies 
    union all 
    select id, trial_id, 'portal' from portalemaillog 
    union all 
    select id, trial_id, 'trialsite' from trialsite 
    union all 
    select id, trial_id, 'trialsubject' from trialsubject 
) t 
left join trial on trial.id = t.trial_id 
group by name; 

這將返回結果是這樣的:

totalcount | subcount | name  
------------+----------+----------- 
      4 |  2 | portal 
      6 |  4 | trialsite 
      7 |  3 | trialsubject 
     10 |  5 | studies 
+0

工作得很好。感謝那 – ryekayo