选择具有多个主键的行

时间:2019-05-13 19:17:13

标签: sql postgresql

假设我要从组织3中选择具有user_id 1的雇员,并从组织4中选择具有user_id 2的雇员。这就是我目前编写查询的方式:

SELECT * 
FROM employees AS employee
WHERE employee.user_id IN (1, 2)
  AND WHERE employee.organisation_id IN (3, 4)

这是我想要得到的结果:

user_id   | organisation_id
1         | 3
2         | 4

但这就是我得到的:

user_id   | organisation_id
1         | 3
1         | 4
2         | 3
2         | 4

如何编写查询来实现这一目标?

2 个答案:

答案 0 :(得分:4)

您可以使用

SELECT * 
from employees
WHERE (user_id,organisation_id) IN ((1, 3),(2, 4))

答案 1 :(得分:0)

您的条件错误的地方

您的目标基于此条件

SELECT * 
from employees AS employee
WHERE ( employee.user_id  = 1 and organisation_id = 3) 
OR (employee.user_id  = 3 and organisation_id = 4) 

您使用的IN子句等于

SELECT * 
from employees AS employee
WHERE ( employee.user_id = 1 OR employee.user_id = 2 )
AND  (employee.organisation_id = OR  employee.organisation_id = 4)