mysql - 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 select users jack in london jack's id(users.id = 1) or users in dubai dmitry(users.id = 5) using join. how it?

what have tried:

select `u`.`username`, `uc`.`city_id` `users` `u`     inner join `users_cities` `uc` on `u`.`id` = `uc`.`user_id`     inner join `users_cities` `uc1` on `uc1`.`city_id` = `uc`.`city_id` `u`.`id` = 1 

it returns:

username    city_id jack        1 jack        1 

you're close. need join user_cities once query. use where clause determine users or cities wish filter on.

if want city name in result set make additional join user_cities cities.

as joining twice on same result set (user_cities) querying result twice, why getting duplicate 'jacks'.

if not need, adjust where clause determine how filter result set.

select    u.username,    c.city     users u   inner join users_cities uc on u.id = uc.user_id   inner join cities c on uc.city_id = c.id    u.id = 1 -- jack   or u.id = 5 -- dimitry 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -