在SQL join中需要帮助

时间:2015-01-16 18:07:38

标签: sql oracle

我有两个表和记录,如下所示:

            User
   ---------------------
         ID     UserId
   ---------------------
          1      User1
          2      User2

          Department_User
   ------------------------------
         ID DEPT_ID       USER_ID
   ------------------------------
          1  1              1
          2  2              1
          3  1              2

现在我想要一个oracle查询,它只返回那些在两个部门(1和2)中服务的用户,在这个例子中它将是1

4 个答案:

答案 0 :(得分:3)

这是set-within-sets查询的示例。我想使用group byhaving来解决这些问题。这是一种方法:

select user_id
from department_user
where dept_id in (1, 2)
group by user_id
having count(distinct dept_id) = 2;

答案 1 :(得分:0)

select du1.user_id
from department_user du1
where exists (
select *    from department_user du2
where dept_id= 2  on   du1.user_id = du2.user_id);
and du1.dept_id = 1

select user_id
from department_user
where dept_id = 1
and user_id in (
select user_id
from department_user
where dept_id= 2);

select du1.user_id
from department_user du1
join department_user du2 on du1.user_id = du2.user_id
where du1.dept_id=1 and  du2.dept_id = 2

我不了解Oracle,但存在的版本可能是SQL Server中最快的版本。如果需要dept_id = 2的记录中的字段以及dept_id = 1

的记录,则需要使用连接版本

答案 2 :(得分:0)

SELECT USER_ID
FROM
(
SELECT USER_ID, DEPT_ID
FROM TABLE
GROUP BY USER_ID, DEPT_ID
HAVING COUNT(*) = (SELECT COUNT(DISTINCT DEPT_ID) FROM TABLE)
)

答案 3 :(得分:-1)

我认为你应该在where子句中使用“AND”运算符来确保select语句满足以下两个条件...查询...

  Select U.ID, U.UserId
  From User U 
  Inner Join Department_User D 
  On U.ID=D.USER_ID 
  Where D.DEPT_ID =1 And D.DEPT_ID = 2