简体   繁体   中英

Many-to-Many Select

I have 3 tables:

users :

id  name
1   Jack
2   Vasya
3   John
4   Robert
5   Dmitry
6   Dylan

cities :

id  city
1   London
2   Kyiv
3   New-York
4   Chicago
5   Moscow
6   Dubai

users_cities :

user_id city_id
1       1
3       1
5       6
2       3
4       5
6       6

I need to select users with Jack in London by Jack's id(users.id = 1) or users in Dubai with Dmitry(users.id = 5) using JOIN. How could I do it?

What I have tried:

SELECT `u`.`username`, `uc`.`city_id` FROM `users` as `u`
    INNER JOIN `users_cities` as `uc` ON `u`.`id` = `uc`.`user_id`
    INNER JOIN `users_cities` as `uc1` ON `uc1`.`city_id` = `uc`.`city_id`
WHERE `u`.`id` = 1

It returns:

username    city_id
Jack        1
Jack        1

You're so very close. You only need to JOIN to user_cities once for your query. Then use the WHERE clause to determine the users or cities you wish to filter on.

If you want the city name in the result set then make an additional join from user_cities to cities .

As you are joining twice on the same result set ( user_cities ) you are effectively querying that result twice, which is why you are getting duplicate 'Jacks'.

If this is not exactly what you need, then adjust your WHERE clause to determine how you would like to filter the result set.

SELECT 
  u.username, 
  c.city 
FROM 
  users as u
  INNER JOIN users_cities as uc ON u.id = uc.user_id
  INNER JOIN cities as c ON uc.city_id = c.id
WHERE 
  u.id = 1 -- Jack
  OR u.id = 5 -- Dimitry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM