MySQL 三个表的连接
我有一些使用连接表具有“具有并属于许多”类型关系的表。主要表格是国家、计划和列表。基本结构是:
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
当给定国家 id 值(在本例中为 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'
我需要做的只是仅返回该国家/地区的程序(仅当特定国家/地区的程序 )该国家/地区实际上也有该国家/地区的任何列表。因此,它应该仅返回程序位于指定国家/地区并且包含该程序和该国家/地区的列表的情况。
如果指定国家/地区的程序没有列表,那么我不希望将其返回。我一直在尝试各种组合,但似乎无法使其发挥作用。有谁知道这是如何做到的?
我想我需要加入列表,但我尝试过的都没有接近。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了避免返回重复数据,我将使用
EXISTS
子句。另外,切换到INNER
连接以满足国家/地区要求。我省略了对
countries
的连接,因为您只处理countries_programs
中提供的国家/地区 ID。To avoid returning duplicate data, I'd use an
EXISTS
clause. Also, switch toINNER
joins to satisfy the country requirement.I've omitted the join to
countries
as you're only dealing with the country ID which is available incountries_programs
.