SELECT 'table_1' as FlowStepCount, COUNT(fs.ID)
FROM [FlowSteps] fs
where fs.FlowID = 120
UNION all
SELECT 'table_2' as FlowStepAssignmentCount, COUNT(fsa.ID)
FROM [FlowStepAssignments] fsa
where fsa.FlowStepID IN (select ID from [FlowSteps] where FlowID = 120)
我想显示如下查询:
FlowStepCount FlowStepAssignmentCount
18 64
我还希望将FLOW表的ID加入FLOWSTEP表的FlowID。我试图加入3表但无法解决它。
我实际上想写这样的查询:
SELECT
count(fs.ID) as FlowStepCount,
count(fsa.ID) as FlowStepAssignmentCount
FROM
[Flow] f,
[FlowSteps] fs,
[FlowStepAssignments] fsa
WHERE
fs.ID = fsa.FlowStepID AND
f.ID = fs.FlowID AND
f.ID = 120
有什么建议吗?如何加入3个表并获取它们的计数(*)只是给出FlowID?
答案 0 :(得分:2)
这可以解决您的问题:
SELECT count(distinct fs.ID) as FlowStepCount,
count(distinct fsa.ID) as FlowStepAssignmentCount
FROM [Flow] f left join
[FlowSteps] fs
on f.ID = fs.FlowID left join
[FlowStepAssignments] fsa
on fs.ID = fsa.FlowStepID
WHERE f.ID = 120;
通常使用子查询的方式更有效:
select (select count(*) from FlowSteps fs where f.ID = fs.FlowID) as FlowStepCount,
(select count(*) from FlowStepAssignments fsa where f.ID = fsa.FlowID) as FlowStepAssignmentCount,
from Flow f
where f.id = 120;