I don't know if the title makes any sense, but here is the situation: See 2 tables below
People: (BTW, if it helps to know, this table will never have >1000 rows)
+----+---------+-------------------+---------+
| id | name | address | city_id |
+----+---------+-------------------+---------+
| 1 | person1 | some address | 123 |
| 2 | person2 | another address | 542 |
| 3 | person3 | different address | 623 |
+----+---------+-------------------+---------+
Cities: (this one may contain all cities with states(and addl. column for country) around the globe)
+-----+-------+--------+
| id | city | state |
+-----+-------+--------+
| 123 | city1 | state1 |
| 542 | city2 | state1 |
| 623 | city3 | state2 |
+-----+-------+--------+
To start, I know only people.id
. Using this I need to find all people that belong to same state
(not same city
). For example, if I have people.id=1
, I need to get all people from the state that person1 (people.id = 1) belongs to:
Output:
+----+---------+-----------------+---------+
| id | name | address | city_id |
+----+---------+-----------------+---------+
| 1 | person1 | some address | 123 | /*Both the people are from state1*/
| 2 | person2 | another address | 542 |
+----+---------+-----------------+---------+
I'm able to achieve this in two queries: A variable $state
storing output of
SELECT c.state from people p INNER JOIN cities c ON p.city_id=c.id where p.id=<my input>;
and then another query
SELECT a.* FROM
peoplea INNER JOIN
citiesb ON a.city_id=b.id WHERE b.state=$state
Is there a more efficient way to achieve this with a single JOIN? I tried combining the two queries to SELECT
with JOIN within a JOIN(in subquery) which doesn't feel right somehow.
P.S: I'm not looking for recommendations on normalization or other changes to schema. All that is already in consideration for another development branch for later upgrade.