N
N
nevro2016-11-02 12:33:45
MySQL
nevro, 2016-11-02 12:33:45

Can IN be replaced by a subquery?

Hotel table:
id | name | cityId
Table of cities:
id | name
Task: to select all hotels located in the city of Moscow, for example.
Solution: SELECT * FROM hotels WHERE cityId = 12
Problem: There may be more than one Moscow (in this example, we do not take into account the country), in addition, it can also be written in Latin.
New solution:
1.

SELECT * FROM cities WHERE name = 'Москва' or name = 'Moscow';

Got a set of records. I manually copied their IDs to:
2. SELECT * FROM hotels WHERE cityId in (12, 19, 23)
There can be many such IDs. It would be great to automate via a subquery, but the subquery should only return one value (just started reading Graber). If you add GROUP BY, then the subquery will return only one value.
But WHERE c IN behaves like a loop, iterates over an "array" of codes... How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2016-11-02
@karminski

SELECT * FROM hotels WHERE cityId IN (SELECT id FROM cities WHERE name = 'Москва' or name = 'Moscow')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question