【问题标题】:How to write the query to count the number of specific records in another table without foreign key?如何编写查询来计算另一个表中没有外键的特定记录的数量?
【发布时间】:2014-06-14 14:21:15
【问题描述】:

下面是我的 Db 的 er 图 我想从表 Subscription 中获取给定 Subscription.ClientId 的所有结果,以及该 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 的链接 [注意:我删除了表订阅屏幕]

我想要的输出是

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

【问题讨论】:

  • 考虑在sqlfiddle.com 中提供一些示例数据以及来自给定示例数据的问题的预期结果集。

标签: mysql yii yii-cactiverecord


【解决方案1】:

试试下面的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多