我需要运行一系列查询。它们是单调的,几乎所有它们都使用相同的外键(trial_id)。有没有办法将所有这些单独的查询转换为一个查询,该查询将发布我需要的所有结果?
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 :(得分: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