在 SQL 服务器中筛选多行
Filter multiple rows in SQL Server
这是我的 table:
filteredID 是筛选行所依据的条件。但是,如果某一行符合条件,我想删除具有相同 staffID 的所有行。
例如,如果 filteredID 设置为 50 或 88.I 想要过滤所有 "james" 行。
所以我的输出将是:
想不出解决这个问题的优雅方法。
实现此结果的最简单方法是在 where 子句中使用 'not in' 运算符
select
staffID, Name
from
Staff
where
staffID not in (select staffID from Staff where filteredID = 50)
order by
staffID;
就这么简单:
declare @my_table table (
filteredID int,
staffID int,
Name varchar(30)
);
insert into @my_table values
(50, 205, 'james'),
(88, 205, 'james'),
(57, 16371, 'jake'),
(55, 16371, 'jake'),
(83, 20817, 'jane'),
(87, 20924, 'jason'),
(49, 21074, 'jackson'),
(42, NULL, 'Foo'),
(170, NULL, 'Goo');
declare @filteredID int = 50;
delete from @my_table
where staffID in (
select staffID
from @my_table
where filteredID = @filteredID
);
select staffID, Name from @my_table;
假设 staffID
是不可为空的列,您可以通过子查询简单地实现它
DECLARE @filteredID INT
SET @filteredID = 50 --Or another value
DELETE FROM TABLE_NAME
WHERE
(
staffID IN (SELECT staffID FROM TABLE_NAME WHERE filteredID =@filteredId)
);
SELECT * FROM TABLE_NAME
这是我的 table:
filteredID 是筛选行所依据的条件。但是,如果某一行符合条件,我想删除具有相同 staffID 的所有行。 例如,如果 filteredID 设置为 50 或 88.I 想要过滤所有 "james" 行。
所以我的输出将是:
想不出解决这个问题的优雅方法。
实现此结果的最简单方法是在 where 子句中使用 'not in' 运算符
select
staffID, Name
from
Staff
where
staffID not in (select staffID from Staff where filteredID = 50)
order by
staffID;
就这么简单:
declare @my_table table (
filteredID int,
staffID int,
Name varchar(30)
);
insert into @my_table values
(50, 205, 'james'),
(88, 205, 'james'),
(57, 16371, 'jake'),
(55, 16371, 'jake'),
(83, 20817, 'jane'),
(87, 20924, 'jason'),
(49, 21074, 'jackson'),
(42, NULL, 'Foo'),
(170, NULL, 'Goo');
declare @filteredID int = 50;
delete from @my_table
where staffID in (
select staffID
from @my_table
where filteredID = @filteredID
);
select staffID, Name from @my_table;
假设 staffID
是不可为空的列,您可以通过子查询简单地实现它
DECLARE @filteredID INT
SET @filteredID = 50 --Or another value
DELETE FROM TABLE_NAME
WHERE
(
staffID IN (SELECT staffID FROM TABLE_NAME WHERE filteredID =@filteredId)
);
SELECT * FROM TABLE_NAME