How to write the query to count the number of specific records in another table without foreign key?

170 Views Asked by At

Below is the er diagram of my Db ER-diagram I want to get all the results from table Subscription for given Subscription.ClientId with number of Assigned.ScreenId for each Subscription.RouteId for that Subscription.ClientId. I have tried the code below, I also tried adjusting relations but with no success, How can I do it in 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

Here is the link to sample http://sqlfiddle.com/#!2/38f2e7 [note:I removed table subscribedscreens]

What i want as output is

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

There are 1 best solutions below

0
On

Have a go with the below sql, and if the result is not what you're after then maybe clarify the results you were expecting.

-- 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

Results:

ROUTEID   CLIENTID   COUNT(ASSIGNED.SCREENID)
   2         1         4
   2         1         2
   2         1         6
   1         2         2