从两个表中选择记录

时间:2015-09-14 12:51:25

标签: mysql sql

我有两张桌子:

个人

ID        |NAME       
|A2112    |John       
|B3200    |Mary       
|C2454    |Bob        
|F2256    |Joe        

工作

|ID        |NAME          |PEOPLE 
|56565     |Taxi Driver   |A2112
|23232     |Herborist     |A2112  
|12125     |Jumper        |B3200  
|25425     |Taxi Driver   |C2454  
|12456     |Taxi Driver   |F2256  
|56988     |Herborist     |F2256  
|45459     |Superhero     |F2256  

我想知道如何以高效的方式从拥有JOBS ID 56565和23232的人中选择任何记录。

搜索模式可以是两个或多个作业,记录也可以有其他作业。

因此,在这个例子中,结果将是John和Joe。

4 个答案:

答案 0 :(得分:6)

我不太确定我是否帮助你。这将返回有工作56565和/或23232的人:

select distinct p.name
from people p
  join jobs j on p.id = j.peopleid
where j.id in (56565, 23232)

如果需要同时工作:

select p.name
from people p
  join jobs j on p.id = j.peopleid
where j.id in (56565, 23232)
group by p.name
having count(*) > 1

HAVING子句也可以写成

having max(j.id) <> min(j.id)

也许这样的表现更好。

答案 1 :(得分:4)

INNER JOIN关键字选择两个表中的所有行,只要两个表中的列匹配即可。

DoCmd.Restore
INNER JOIN的

Visual explanation

Visual explanation of INNER JOIN

答案 2 :(得分:0)

    SELECT * FROM PEOPLE as p
    JOIN JOB as j ON j.PEOPLE = p.ID
    WHERE j.ID IN(56565, 23232)

答案 3 :(得分:0)

&#34;拥有 JOBS&#34;的人转换为SQL中的WHERE EXISTS

select *
from people
where exists
(
  select *
  from jobs
  where jobs.people = people.id
  and jobs.id in (56565, 23232)
);

这也可以用IN子句编写,我甚至认为它的简单性稍微可读:

select *
from people
where id in
(
  select people
  from jobs
  where id in (56565, 23232)
);