从一个表删除另一表的数据

时间:2018-12-11 07:10:38

标签: sql sql-server

我有2张桌子。例如,员工和用户。 EmployeeId,Status是两个表中的公用字段。我需要签入Employee表并维护User表中的数据。

例如:

Employee
-------------
EmployeeId    Status     EmpName
1111          Active     Mary
1112          Active     Joseph
1113          Inactive   Elizabeth 

User
-------------
EmployeeId    Status     UserName
1111          Active     Mary
1114          Active     Rachel

如果员工表中已有数据,我想消除用户表中的数据。

结果应该是

TmpUser
-------------
EmployeeId    Status     UserName
1114          Active     Rachel

请帮助编写查询。

预先感谢

3 个答案:

答案 0 :(得分:1)

您可以写:

delete User
where EmployeeId in
(
     select EmployeeId from Employee
)

答案 1 :(得分:1)

另一种编写方式:

create table #Employee (empid int, sta varchar(50), empname varchar(50))
insert into #Employee
values

(1111        ,'Active',     'Mary'),
(1112        ,'Active',     'Joseph'),
(1113        ,'Inactive',   'Elizabeth') 


create table #user (empid int, sta varchar(50), username varchar(50))    
insert into #user

values
(1111         ,'Active','Mary'),
(1114         ,'Active','Rachel')

delete from #user 
where exists (select empid from #Employee b where #user.empid = b.empid)

答案 2 :(得分:1)

尝试一下:

--If you want only print you can do it
select f1.* 
from User f1 left outer join Employee f2 on f1.EmployeeId=f2.EmployeeId
where f2.EmployeeId is null

--If you want remove you can do it
delete f1 
from User f1 inner join Employee f2 on f1.EmployeeId=f2.EmployeeId