[英]How to delete rows from one table matching another table?
I am trying to delete rows from one table. 我正在尝试从一个表中删除行。 So this what i have done so far.
所以这是我到目前为止所做的。 I imported a .CSV file which created a temp table.
我导入了创建临时表的.CSV文件。 I would like to delete the rows in my original table with matching with temp table.
我想删除与临时表匹配的原始表中的行。
I tried the following code : 我尝试了以下代码:
Delete From Table1
Where postid and userid in (Select postid, userid
from Table2)
but it does not work. 但它不起作用。
The goal is to delete rows in Table 1 using Table 2. 目标是使用表2删除表1中的行。
A simple INNER JOIN
should do the job: 一个简单的
INNER JOIN
应该可以完成这项工作:
DELETE T1
FROM Table1 T1
INNER JOIN Table2 T2
ON T1.postid = T2.postid
AND T1.userid = T2.userid
This is just another funny way : 这只是另一种有趣的方式:
DELETE FROM Table1
WHERE STR(postid) + STR(userid)
IN (SELECT STR(postid) + STR(userid) FROM Table2)
As far as I understand you want to Delete from Table1 where you want to create a composite condition based on postid and userid the from Table2 the problem is that you subquery in(Select postid,userid from Table2) is not returning the correct value as to match the in condition please modify the query to 据我了解,您想从Table1中删除,而您要在其中基于postid和userid创建一个组合条件,则要从Table2中删除,问题是您的子查询(从Table2中选择postid,userid)没有返回正确的值符合条件,请将查询修改为
DELETE T1
FROM Table1 T1
INNER JOIN Table2 T2
ON T1.postid = T2.postid
AND T1.userid = T2.userid
as stated in the previous answer 如上一个答案所述
You can use a Merge statement. 您可以使用Merge语句。 In this case you're only interested in deletes.
在这种情况下,您只对删除感兴趣。 A semicolon is required after the delete section, followed by a final semicolon to end the merge statement.
在delete节之后需要使用分号,然后使用最后一个分号来结束merge语句。 For example:
例如:
MERGE table1 AS target USING table2 AS source
ON target.postid = source.postid and target.userid = source.userid
WHEN Matched THEN DELETE;;
An example sqlfiddle: http://sqlfiddle.com/#!18/a932d/1/0 sqlfiddle示例: http ://sqlfiddle.com/#!18/a932d/1/0
The Merge documentation: https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql 合并文档: https : //docs.microsoft.com/zh-cn/sql/t-sql/statements/merge-transact-sql
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.