我一直试图在MySQL上搞定。
它们存储在3个不同的表(国家,城市,社区)中,可以通过country.country_link = city.country_link和city.city_link = community.city_link
连接在一起有时需要添加国家/地区过滤器,如下所示
我试过这个,但仍无济于事:
SELECT
tbl_country.country_link AS country_link,
tbl_city.city_link as city_link,
tbl_community.community_link
FROM
tbl_country
LEFT JOIN
tbl_city ON tbl_country.country_link = tbl_city.country_link
LEFT JOIN
tbl_community ON tbl_city.city_link = tbl_community.city_link
WHERE
tbl_city.country_code = 'AE'
UNION
SELECT
tbl_country.country_link AS country_link,
tbl_city.city_link as city_link,
tbl_community.community_link
FROM
tbl_country
LEFT JOIN
tbl_city ON tbl_country.country_link = tbl_city.country_link
LEFT JOIN
tbl_community ON tbl_city.city_link = tbl_community.city_link
WHERE
tbl_city.city_link IS NULL AND
tbl_community.community_link IS NULL AND
tbl_city.country_code = 'AE'
UNION
SELECT
tbl_country.country_link AS country_link,
tbl_city.city_link as city_link,
tbl_community.community_link
FROM
tbl_country
LEFT JOIN
tbl_city ON tbl_country.country_link = tbl_city.country_link
LEFT JOIN
tbl_community ON tbl_city.city_link = tbl_community.city_link
WHERE
tbl_community.community_link IS NULL AND
tbl_community.community_link IS NULL AND
tbl_city.country_code = 'AE'
答案 0 :(得分:1)
根据上面的评论,我在你的sql脚本中进行了更改。观察现在在连接级别条件下移动的WHERE子句条件。
SELECT tbl_country.country_link AS country_link,
tbl_city.city_link as city_link,
tbl_community.community_link
FROM tbl_country
LEFT JOIN tbl_city ON tbl_country.country_link = tbl_city.country_link AND tbl_city.country_code = 'AE'
LEFT JOIN tbl_community ON tbl_city.city_link = tbl_community.city_link
UNION
SELECT tbl_country.country_link AS country_link,
tbl_city.city_link as city_link,
tbl_community.community_link
FROM tbl_country
LEFT JOIN tbl_city ON tbl_country.country_link = tbl_city.country_link
LEFT JOIN tbl_community ON tbl_city.city_link = tbl_community.city_link AND
tbl_community.community_link IS NULL AND tbl_city.country_code = 'AE'
UNION
SELECT tbl_country.country_link AS country_link,
tbl_city.city_link as city_link,
tbl_community.community_link
FROM tbl_country
LEFT JOIN tbl_city ON tbl_country.country_link = tbl_city.country_link
LEFT JOIN tbl_community ON tbl_city.city_link = tbl_community.city_link AND
tbl_community.community_link IS NULL AND
tbl_community.community_link IS NULL AND
tbl_city.country_code = 'AE'