如何编写查询来计算没有外键的另一个表中特定记录的数量?

时间:2014-06-14 14:21:16

标签: mysql yii yii-cactiverecord

下面是我的Db的图表 ER-diagram 我想从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的链接[注意:我删除了表subscribedscreens]

我想要的输出是

RouteId ClientId NumScreen NumAds... (Count(assignedScreenid)for given route)
1        1                              2
2        1                              1
1        2                              1
2        2                              3

1 个答案:

答案 0 :(得分:0)

请使用以下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