我有如下所述的表格:
subscription_plans (存储所有计划的表格)
id plan days_limit added_on status rate
------------------------------------------------
1 PlanA 15 1398249706 1 150.00
2 PlanB 15 1398249706 1 150.00
subscribed_videos (每个计划中存储视频详情的表格)
id plan_id videoid
----------------------
1 1 1
2 2 2
subscription_groups (用于存储计划可以成为另一计划的一部分的组的表。即,计划A是包含其他2个计划的计划,计划B和C)
id plan_id assosiated_plan_id added_on
----------------------------------------------
1 1 2 1398249706
usersubscription (用于存储用户订阅计划的表)
id user_id plan_id subscribed_on
---------------------------------------
1 1 1 1398771106
现在,我的问题是如何获得每个计划的视频数量。如果计划A包含计划B和C( subscription_groups 表),则计数应返回该特定计划中每个计划的总视频计数。现在我已经完成了一个查询,该查询将返回计划详细信息以及计划的视频数量,但我无法将其与 subscription_groups 一起加入。如何在单个查询中完成此操作。
$data['planquery']=$this->db->query("select
us.plan_id,us.subscribed_on,sp.plan,sp.days_limit,sp.rate,count(sv.videoid) from
usersubscription as us INNER JOIN
subscription_plans as sp ON us.plan_id=sp.id INNER JOIN subscribed_videos as sv ON sp.id=sv.plan_id where sp.status=1 and us.user_id=1");
预期结果:
plan_id subscribed_on plan days_limit rate count
-------------------------------------------------------
1 1398771106 PlanA 15 150.00 2
任何人都可以帮我找到解决方案吗?
提前致谢。
答案 0 :(得分:2)
你可以这样做
SELECT
us.plan_id,
us.subscribed_on,
sp.plan,
sp.days_limit,
sp.rate,
COUNT(sv.videoid)
FROM
usersubscription AS us
RIGHT JOIN subscription_plans AS sp
ON us.plan_id = sp.id
INNER JOIN subscribed_videos AS sv
ON sp.id = sv.plan_id
INNER JOIN subscription_groups g
ON(g.plan_id =sv .plan_id OR sv.plan_id= g.assosiated_plan_id)
WHERE sp.status = 1
AND (us.user_id = 1 OR us.user_id IS NULL )
由于用户只有计划关联,但关联的计划也可以链接另一个计划,因此最后一个条件将检查用户ID,但是对于第二个链接计划,为空,因为右边连接{} { 1}}
修改
subscription_plans
对于视频ID,您可以使用group_concat
SELECT
u.plan_id,
u.subscribed_on,
p.plan,
p.days_limit,
p.rate
,COUNT(DISTINCT v.`videoid`)
FROM `usersubscription` u
JOIN `subscription_groups` g
ON (u.`plan_id` = g.`plan_id`)
RIGHT JOIN `subscription_plans` p
ON(u.`plan_id` = p.`id` OR g.`assosiated_plan_id` = p.`id`)
INNER JOIN `subscribed_videos` v ON(v.`plan_id`=g.`assosiated_plan_id` OR u.`plan_id`= v.`plan_id`)
WHERE u.`id`=1 AND p.`status` = 1