下面是我的Db的er图
我想从给定Subscription.ClientId的表Subscription中获取所有结果,并为该Subscription.ClientId的每个Subscription.RouteId分配Assigned.ScreenId的数量。
我已经尝试了下面的代码,也尝试了调整关系,但是没有成功,我该如何在yii中做到这一点。
SELECT S. * , (
SELECT COUNT( C.ScreenId )
FROM (
SELECT B.ScreenId, A.RouteId, B.clientId
FROM Screens AS A
INNER JOIN Assigned AS B ON A.ScreenId = B.ScreenId
) AS C
WHERE S.RouteId = C.RouteId
) AS couNTER
FROM Subscription AS S
LIMIT 0 , 30
这是示例http://sqlfiddle.com/#!2/38f2e7的链接[注意:我删除了表subscriptionsscreens]
我想要的输出是
RouteId ClientId NumScreen NumAds... (Count(assignedScreenid)for given route)
1 1 2
2 1 1
1 2 1
2 2 3
最佳答案
使用下面的sql,如果结果不是您想要的,则可以澄清您期望的结果。
-- SELECT subscription.SubscriptionId, client.clientId, assigned.ScreenId, route.RouteId
SELECT route.RouteId, client.clientId, COUNT(assigned.ScreenId)
FROM subscription
LEFT JOIN client ON client.ClientId = subscription.ClientId
LEFT JOIN assigned ON assigned.ClientId = client.ClientId
LEFT JOIN route ON route.RouteId = subscription.RouteId
GROUP BY assigned.ScreenId
结果:
ROUTEID CLIENTID COUNT(ASSIGNED.SCREENID)
2 1 4
2 1 2
2 1 6
1 2 2
关于mysql - 如何编写查询以计算另一个表中没有外键的特定记录数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24220850/