Question

I have problem with this select. If anybody help, it would be great:

There are tables called BUNDLE, COURSE and BUNDLE_COURSE

The BUNDLE contain information like price, discount etc. The COURSE contain information like title, icon_path etc.

The BUNDLE_COURSE table is link table and one bundle contain more COURSES.

Example:

BUNDLE  | BUNDLE_COURSE| COURSE
--------+--------------+----------
1       | 1,5          | 5
2       | 1,6          | 6
        | 1,7          | 7
        | 2,5          | 8
        | 2,7          |
        | 2,8          | 

I need to get only BUNDLES, where all COURSES meet conditions (For example: course_date > CURRENT_DATE)

How can I do that?

Was it helpful?

Solution

You could select all bundles where no course exists that does not meet the criteria:

select  *
from    bundles b
where   not exists
        (
        select  *
        from    courses c
        where   c.id = b.course
                and course_date < getdate() -- Note inverse condition
                and ...
        )

A good article on this is Divided We Stand: The SQL of Relational Division.

OTHER TIPS

You can do this using aggregation and a having clause. Here is an example using your condition:

select b.bundleid
from bundle b join
     bundle_course bc
     on b.bundleid = bc.bundleid join
     course c
     on bc.courseid = c.courseid
group by b.bundleid
having min(c.coursedate) >= CURRENT_DATE;

If you wanted to add more conditions, that is easy. For instance, if you wanted bundles with the above condition and at least three courses:

having min(c.coursedate) >= CURRENT_DATE and
       count(*) >= 3;

If you wanted at least one course to have the word "SQL" in the title:

having min(c.coursedate) >= CURRENT_DATE and
       count(*) >= 3 and
       sum(case when c.title like '%SQL%' then 1 else 0 end) > 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top