通过用户查找用户与一个国家/地区的所有城市相关的城市关系的国家/地区

时间:2017-09-05 23:44:53

标签: mysql sql doctrine-orm orm dql

我有四个表:用户,国家,地区和城市

国家有许多地区有很多城市。

用户可以与0对多城市(希望访问)相关。

如何编写MySQL查询(或DQL),找出用户完全与他们相关的地区和国家/地区,即希望访问他们的所有城市?

4 个答案:

答案 0 :(得分:1)

对于地区,可以很容易地将城市数量与最大城市数量进行比较

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'

你可以对国家做同样的事情。如果你想不通,请告诉我。

答案 1 :(得分:1)

使用NOT EXISTSLEFT 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
)

答案 2 :(得分:0)

User级别开始。然后加入更大的实体,并使用distinct来减少重复。

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)

答案 3 :(得分:0)

使用联接

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