MySQL-在第二张表中选择具有特定值的行

时间:2018-10-30 20:27:39

标签: mysql filter

假设我有这两个表:

人:

id | name
---------
1  | John 
2  | Jack
3  | Pepe

jobs_people_relations:

job | person
------------
15  | 1
16  | 1
15  | 2
16  | 3

我想选择所有拥有#15和#16工作的人,但没有一个只有#15或只有#16工作的人。这意味着我想接待约翰。我该如何实现?

3 个答案:

答案 0 :(得分:0)

  • 您可以对人员详细信息进行Group By
  • Having子句中使用条件聚合来过滤某人具有job = 15 AND job = 16的情况。

请尝试以下操作:

SELECT
  p.id, 
  p.name 
FROM people AS p
JOIN jobs_people_relations AS jpr ON jpr.person = p.id 
GROUP BY p.id, p.name 
HAVING 
  SUM(jpr.job = 15) AND 
  SUM(jpr.job = 16)

答案 1 :(得分:0)

您的示例似乎有点含糊,但是在T-SQL中,您可以尝试

Select 
Distinct name 
From people 
Inner Join jobs_people_relations 
On people.id = jobs_people_relations.person
Where people.id = 1

答案 2 :(得分:0)

这应该有效:

select p.id, p.name from people p
join jobs_people_relations r on p.id = r.person
where r.job in(15,16)
group by id, name
having count(*) = 2