表 - 我删除了查询不需要的其他字段:
church (id, name)
delegate (id, orderId, churchId, status)
orders (id, eventId)
event (id, name)
变量ddEvent在运行时包含事件名称(不是eventId)
我想要一份完整的教会名单列表,其中包含代表人数(如果有的话)进入特定活动,其状态为“付费”,“开始”和“开始”。或者'已完成'
我试过这个:
select church.name as 'Church Name', count(delegate.id) as Delegates
from church
left join delegate on church.id = delegate.churchId and (delegate.status = 'Paid' or delegate.status = 'Started' or delegate.status = 'Completed')
join orders on delegate.orderId = orders.id
join event on orders.eventId = event.id AND event.Name = 'ddEvent'
group by church.id
然而,这并没有产生正确的结果
答案 0 :(得分:0)
尝试对2个相关表进行左连接。
select church.name as 'Church Name', count(delegate.id) as Delegates
from church
left join delegate on church.id = delegate.churchId
and (delegate.status = 'Paid' or delegate.status = 'Started' or delegate.status = 'Completed')
left join orders on delegate.orderId = orders.id
left join event on orders.eventId = event.id
where event.Name = 'ddEvent'
group by church.id
@Barmar谢谢你!
答案 1 :(得分:0)
如果您需要计算参加某个活动的代表人数,那么您无法在代表之间进行左联接直至活动。这些连接需要是内连接。
您必须做的是围绕联接的顺序,确保delegate - orders - events
表首先加入内部,然后将它们的组合结果保留在{ {1}}。您需要在church
子句中使用括号来实现此目的:
from
请注意我如何将select church.name as 'Church Name', count(delegate.id) as Delegates
from church
left join (delegate
inner join orders on delegate.orderId = orders.id
inner join event on orders.eventId = event.id AND event.Name = 'ddEvent') on church.id = delegate.churchId and (delegate.status = 'Paid' or delegate.status = 'Started' or delegate.status = 'Completed')
group by church.id
子句加入on
表和church
表移动到delegate
子句的末尾。