PostgreSQL子查询一对多关系搜索

时间:2013-06-29 18:48:26

标签: sql postgresql one-to-many

employee_id | first_name | last_name
--------------------------------------
00001         Tim          Smith
00002         John         Doe

employee_id | skill_id
--------------------------------------
00001         1
00001         2
00002         1
00002         3

skill_id | name
--------------------------------------
1          Java
2          PHP
3          MySQL

我想选择具有Java AND PHP技能的所有员工。上面的示例应该返回

employee_id | first_name | last_name
--------------------------------------
00001         Tim          Smith

我如何在PostgreSQL中执行此操作?

1 个答案:

答案 0 :(得分:1)

尝试

SELECT e.employee_id, e.first_name, e.last_name
  FROM employee e JOIN employee_skills es
    ON es.employee_id = e.employee_id JOIN skills s
    ON es.skill_id = s.skill_id
 WHERE s.name IN('PHP', 'Java')
 GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(DISTINCT s.skill_id) = 2

如果在你的用户界面中你已经知道你可能做过的技巧,因为你有ref table,那么你甚至不需要第二次加入

SELECT e.employee_id, e.first_name, e.last_name
  FROM employee e JOIN employee_skills es
    ON es.employee_id = e.employee_id 
 WHERE es.skill_id IN(1, 2)
 GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(DISTINCT es.skill_id) = 2

输出:

| EMPLOYEE_ID | FIRST_NAME | LAST_NAME |
----------------------------------------
|           1 |        Tim |     Smith |

这是 SQLFiddle 演示