Reputation: 714
I have some tables that have 'has and belongs to many' type relationships using join tables. The main tables are countries, programs and listings. The basic structure is:
countries
-id
-name
programs
-id
-name
listings
-id
-title
countries_programs
-country_id
-program_id
listings_programs
-listing_id
-program_id
listings_countries
-listing_id
-country_id
I have been doing the following to list the programs for a country when given the country id value (in this case 5):
SELECT programs.*
FROM programs
LEFT JOIN countries_programs ON programs_id = countries_programs.program_id
LEFT JOIN countries ON countries.id = countries_programs.country_id
WHERE countries_id = '5'
What I need to do is only return programs for the country only if the programs for the specific country actually have any listings that are also in that country. So it should return only the case where the programs are in the country specified and have listings that are in that program and also in that country.
If a program for the specified country has no listings, then I don't want it returned. I've been trying various combinations, but can't seem to get this to work. Does anyone see how this could be done?
I think I need to join the listings table, but nothing I've tried has come close.
Upvotes: 0
Views: 255
Reputation: 164731
To avoid returning duplicate data, I'd use an EXISTS
clause. Also, switch to INNER
joins to satisfy the country requirement.
SELECT p.*
FROM programs p
INNER JOIN countries_programs cp
ON p.id = cp.program_id
WHERE cp.country_id = 5
AND EXISTS (
SELECT 1 FROM listings_countries lc
INNER JOIN listings_programs lp
ON lc.listing_id = lp.listing_id
WHERE lc.country_id = c.id
AND lp.program_id = p.id
)
I've omitted the join to countries
as you're only dealing with the country ID which is available in countries_programs
.
Upvotes: 1