我有以下数据库结构
table_countries
----------
country_id
country_name
table_cities
----------
city_id
country_id
city_name
table_streets
----------
street_id
city_id
street_name
table_people
----------
person_id
street_id
person_name
Run Code Online (Sandbox Code Playgroud)
有多个国家,可以有多个城市,而这些城市又有多条街道等等.
我希望执行一个查询,该查询将获得其中包含1个或更多人的所有国家/地区的列表.
问题是国家表没有直接链接到人员表.LEFT JOIN为同一个国家/地区返回多行.
对于编辑中提到的预期结果,我将左连接更改为内连接,并仅选择具有group by子句的国家/地区名称.注意on子句中的外键名称,我认为你必须澄清/纠正你的表结构:
SELECT
table1.country
FROM
table1 JOIN table2 ON table1.id = table2.table1_id
JOIN table3 ON table2.id = table3.table2_id
JOIN table4 ON table3.id = table4.table3_id
GROUP BY
table1.country
Run Code Online (Sandbox Code Playgroud)