我有四个表:用户,国家,地区和城市
国家有许多城市。
用户可以与0到多个城市有关(希望访问)。
我如何编写一个MySQL查询(或DQL),该查询(或DQL)找到了用户是完全的国家/地区,即希望访问所有城市?
使用NOT EXISTS
和LEFT JOIN
SELECT *
FROM Region r
WHERE NOT EXISTS(
SELECT 1
FROM City c
LEFT JOIN User u ON c.id_city = u.id_city and u.id_user = 'user_id'
WHERE c.id_reg = r.id_reg and u.id_user IS NULL
)
这只会找到用户希望访问所有城市的区域,但是,如果您想要各个国家,那只是一个微小的修改
SELECT *
FROM Country ctr
WHERE NOT EXISTS(
SELECT 1
FROM Region r
LEFT JOIN City c ON r.id_reg = c.id_reg
LEFT JOIN User u ON c.id_city = u.id_city and u.id_user = 'user_id'
WHERE ctr.id_country = r.id_country and u.id_user IS NULL
)
对于区域,很容易将城市数与最大城市数量进行比较
SELECT user_id,
Region_count.region_id
FROM User
JOIN
(SELECT user_id, region_id, count(*) as reg_user_count
FROM City
WHERE user_id='ThisUser'
GROUP BY region_id) Region_Count
ON Region_Count.user_id=User.user_id
JOIN
(SELECT region_id, count(*) as reg_max
FROM City
GROUP BY region_id) as Region_Max
ON Region_Max.region_id=Region_Count.region_id
AND Region_Max.reg_max=Region_Count.reg_user_count
WHERE user_id='ThisUser'
您可以对国家做同样的事情。让我知道您是否无法弄清楚。
使用加入
select cu.country_name, r.region_name from User u join City c
on u.cityID=c.cityID join Region r on
c.regionID=r.regionID join Country cu
on r.countryID=cu.countryID
where u.userID=SOMEID
从User
级别开始。然后加入越来越大的实体,并使用独特的方式来减少重复。
SELECT distinct
u.user_name
,r.region_name
,co.country_name
FROM users u
LEFT JOIN cities c ON u.wish_to_visit = c.city_name
LEFT JOIN regions r ON c.region = r.region_name
LEFT JOIN countries co ON r.country = co.country_name
WHERE u.user_name = 'John Doe'
编辑:仅查找用户想要访问所有
的国家发布问题更新,让我们只能在用户想要访问其中所有城市的国家/地区拉动。在这种情况下,我们从国家开始,然后向用户努力。然后,我们汇总以查看一个国家的城市被捕获的百分比。
关键是仅加入我们关心的用户(不过要过滤他们,这将消除用户不匹配城市的NULL
)。毕竟,一个简单的HAVING
将帮助我们过滤完全匹配的国家。
SELECT
c.country_name
,count(ci.city_name) as count_all_cities
,count(u.wish_to_visit) as count_user_cities
FROM countries c
LEFT JOIN regions r ON c.country_name = r.country
LEFT JOIN cities ci ON r.region_name = ci.region
LEFT JOIN users u ON ci.city_name = u.wish_to_visit AND u.user_name = 'John Doe'
GROUP BY c.country_name
HAVING count(ci.city_name) = count(u.wish_to_visit)