SQL从2个表

时间:2015-10-08 07:13:20

标签: 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 |
+----+---------+-------------------+---------+

城市(这个城市可能包含全球所有州(以及国家/地区的addl。列))

+-----+-------+--------+
| id  | city  | state  |
+-----+-------+--------+
| 123 | city1 | state1 |
| 542 | city2 | state1 |
| 623 | city3 | state2 |
+-----+-------+--------+

首先,我只知道people.id。使用此功能,我需要找到属于同一state的所有人(不同city )。例如,如果我有people.id=1,我需要让所有来自的人员(person.id = 1)属于:

输出:

+----+---------+-----------------+---------+
| 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 {人{1}} {城市{1}}

使用单个JOIN是否有更有效的方法来实现这一目标?我尝试将两个查询与JOIN(在子查询中)中的JOIN组合到a INNER JOIN,这在某种程度上感觉不对。

P.S:我不是在寻找关于规范化或其他模式更改的建议。所有这些都已经考虑到另一个开发分支以供以后升级。

4 个答案:

答案 0 :(得分:2)

您可以尝试以下查询 -

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>;

注意:对于人员表中的性能ID和city_id,以及城市中的id和状态表应该被编入索引。

另外,对于更多优化,您应该使用state_id而不是state来进行连接,为此您必须在表中创建state_id字段。

答案 1 :(得分:2)

你可以试试这个。

select * from people
where city_id in(
    select city from cities c
    inner join(
        select c.state from people p
        left join cities c on c.city = p.city_id
        where p.id = '1'
    ) s on s.state = c.state
)

答案 2 :(得分:1)

SELECT * 
FROM people p1 
WHERE p1.city_id in (
    SELECT c1.id 
    FROM cities c1 
    WHERE c1.state IN (
        SELECT c2.state 
        FROM people p2,
             cities c2 
        WHERE c2.id = p2.city_id 
          AND p2.id = 1
        )
    );

而不是查询中的p2.id = 1,请从人员表中提供您要获取数据的人员ID。

答案 3 :(得分:0)

Select a.* from 
people as a
inner join (
select cityid from people where personid = <my input>
) as b on b.cityid = a.cityid

- 或 -

WITH CTE as
(
    select cityid from people where personid = <my input>
)

select a.* from people as a
inner join CTE as b on b.cityid = a.cityid;