在我之前的问题中,我询问过如何将查询结果存储在变量中...现在我意识到查询可以返回多行。
我目前有这个:
SELECT @UserId = UserId FROM aspnet_Users WHERE UserName = @username
我想做这样的事情:
DELETE FROM some_table WHERE UserId IN ( *the ID list* )
DELETE FROM some_table_2 WHERE UserId IN ( *the ID list* )
我的第一直觉是使用“GROUP_CONCAT”,但显然这是一个仅限MySQL的功能。有一些方法可以提供相同的功能,但我想知道是否有更好的方法来构建查询?
答案 0 :(得分:4)
SELECT * FROM dbo.aspnet_UsersInRoles
WHERE UserId IN (
SELECT UserId FROM aspnet_Users
WHERE UserName = @username
)
答案 1 :(得分:1)
这应该这样做..
SELECT
*
FROM
dbo.aspnet_UsersInRoles
WHERE
UserId IN (
SELECT
UserId
FROM
aspnet_Users
WHERE
UserName = @username
)
答案 2 :(得分:0)
delete from st
from some_table st
inner join aspnet_Users au
on st.UserId = au.UserId
where /* add additional criteria here to produce "* the ID list *" */
答案 3 :(得分:0)
如果要避免重复子查询,可以将其结果放入临时表或表变量中。例如:
/*declare and fill a table variable containing all user ids you need to manipulate*/
declare @t table(userid int)
insert into @t(userid) select UserId from aspnet_Users where UserName=@username
/*delete from some table by using the temp variable*/
delete from st
from some_table st
inner join @t t
on st.userid = t.userid
/*repeat this for some other table*/
delete from st
from some_other_table st
inner join @t t
on st.userid = t.userid
如果你想避免多个删除语句,如果some_table中不存在some_other_table中的用户id,那么你可以在some_table上创建触发器:
create trigger x on some_table for delete
as
begin
delete from some_other_table
where userid in (select userid from deleted)
end