Question

I have 3 tables as shown below:

subscription_plans

enter image description here

subscribed_videos

enter image description here

subscription_groups

enter image description here

I want to find the plans corresponding to the selected video (table subscription_plans). Table subscription_groups contains the plan-plan mapping ie, a plan can be part of another plan. For example, Plan A, Plan B and Plan C. Plan A contains both Plan B an Plan C and video with id 5 is part of Plan B (table subscribed_videos) , then the query for finding the plans corresponding to video 5 should return Plan A along with Plan B. Also the records should be distinct.

I tried with the following query. But if I am adding a plan which don't have an entry in subscription_groups, then that record is not returning with this query.

$videoid=$_POST['videoid'];
echo "select sv.plan_id,sg.plan_id,sp.id,sp.plan,sp.days_limit,sp.rate from subscribed_videos as sv 
    LEFT JOIN subscription_groups as sg ON sv.plan_id=sg.assosiated_plan_id INNER JOIN 
    subscription_plans as sp ON sv.plan_id=sp.id where sg.assosiated_plan_id=sv.plan_id and sv.videoid=$videoid
    and sg.assosiated_plan_id=sp.id";

Can anyone help me to find the appropriate query for this ? Thanks in advance.

Was it helpful?

Solution

I think subqueries make sense for this query. The first subquery selects the id of the plan of your video and the second subquery selects the ids of the associated plans.

SELECT 
    sp.id,
    sp.plan,
    sp.days_limit,
    sp.rate 
FROM 
    subscription_plans sp
WHERE 
    id IN (SELECT DISTINCT plan_id FROM subscribed_videos sv where sv.videoid = $videoid)
    OR id IN (SELECT DISTINCT assosiated_plan_id 
        FROM subscription_groups sg
        JOIN subscribed_videos sv ON sv.plan_id = sg.plan_id
        WHERE sv.videoid = $videoid)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top