mysql - SQL从2个表的单个查询中的状态中选择地址

标签 mysql sql performance join

我不知道这个标题是否有意义,但情况是这样的:见下面的 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.* FROMa 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/

相关文章:

mysql - 将 Microsoft SQL Server 数据库复制到 Linux 上的 MySQL/PostgreSQL 的选项

mysql - 用一些重复的条目更新 MySQL 表

php - 在此 sql 查询中除以零?

c# - 如何获取 sql 结果并在标题中填充标签?

c# - ConcurrentBag 与 List 的性能比较

c# - LINQ 的 SQL 脚本

php - 无法使用 MysqlResultSet 类型的对象

sql - "materialize view"的最佳方式

mysql - 如何通过一条查询语句从两个相关表中获取矩阵表?

.net - "Spike"探查器?