我不知道这个标题是否有意义,但情况是这样的:见下面的 2 个表格
人:(顺便说一句,如果有帮助的话,这张表永远不会有 >1000 行)
+----+---------+-------------------+---------+
| id | name | address | city_id |
+----+---------+-------------------+---------+
| 1 | person1 | some address | 123 |
| 2 | person2 | another address | 542 |
| 3 | person3 | different address | 623 |
+----+---------+-------------------+---------+
城市:(这个可能包含全局所有有州(和国家/地区的附加列)的城市)
+-----+-------+--------+
| id | city | state |
+-----+-------+--------+
| 123 | city1 | state1 |
| 542 | city2 | state1 |
| 623 | city3 | state2 |
+-----+-------+--------+
开始,我只知道people.id
.使用这个我需要找到属于同一state
的所有人(不一样 city
)。例如,如果我有 people.id=1
,我需要从 person1 (people.id = 1) 所属的 state 获取所有人员:
输出:
+----+---------+-----------------+---------+
| id | name | address | city_id |
+----+---------+-----------------+---------+
| 1 | person1 | some address | 123 | /*Both the people are from state1*/
| 2 | person2 | another address | 542 |
+----+---------+-----------------+---------+
我可以通过两个查询实现这一点:一个变量 $state
存储
SELECT c.state from people p INNER JOIN cities c ON p.city_id=c.id where p.id=<my input>;
然后是另一个查询
SELECT a.* FROM
人a INNER JOIN
城市 b ON a.city_id=b.id WHERE b.state=$state
是否有更有效的方法通过单个 JOIN 实现此目的?我尝试将这两个查询组合到 SELECT
在 JOIN(in subquery) 中使用 JOIN,这在某种程度上感觉不对。
P.S:我不是在寻找关于规范化或其他架构更改的建议。所有这些都已经考虑到另一个开发分支以供以后升级。
最佳答案
您可以尝试以下查询-
SELECT p2.*
FROM people p
JOIN cities c ON p.city_id=c.id
JOIN cities c2 ON c.state=c2.state
JOIN people p2 ON p2.city_id=c2.id
WHERE p.id=<my input>;
注意:对于people表中的performance id和city_id,cities表中的id和state应该被索引。
此外,为了进一步优化,您应该使用 state_id 而不是 state 进行连接,为此您必须在表中创建 state_id 字段。
关于mysql - SQL从2个表的单个查询中的状态中选择地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009008/