可以使用连接查询根据满足条件删除记录吗?
例如,我有一个链接表连接3条记录。我现在的查询删除了这个表中的一个记录,其中一个id不是IN()
内爆的Php数组。我已经意识到,如果数组中不存在id,并且它们属于基于另一个表的链接的某个其他表,则查询应仅从该表中删除记录。
答案 0 :(得分:26)
对于SQL Server,命令略有不同:
DELETE FROM TableA
FROM TableA LEFT OUTER JOIN TableB ON TableA.Column = TableB.Column
WHERE TableB.Column IS NULL
不,这不是拼写错误,是的,你做需要“FROM TableA”两次。至少,您需要第二个FROM(第一个是可选的)。以下优点是它适用于SQL Server和MySQL:
DELETE TableA
FROM TableA LEFT OUTER JOIN TableB ON TableA.Column = TableB.Column
WHERE TableB.Column IS NULL
答案 1 :(得分:9)
我喜欢使用EXISTS子句:
DELETE FROM TableA
WHERE
<<put your array condition here>>
AND NOT EXISTS
(SELECT 1 FROM TableB Where TableB.ID=TableA.ID)
答案 2 :(得分:8)
您可以使用:
DELETE基于加入:
DELETE A
FROM TableA AS A
LEFT OUTER JOIN TableB As B ON A.Id = B.TabaleAId
WHERE B.Column IS NULL
使用子查删除:
DELETE
FROM TableA AS A
Where
A.id not in ( Select B.TabaleAId From Tab;eB As B )
或
DELETE FROM TableA
WHERE Not EXISTS
(
SELECT *
FROM TableB As B
Where B.TableAId = TableA.Id
)
使用表格式删除
With A
As
(
Select TableA.*
FROM TableA AS A
LEFT OUTER JOIN TableB As B ON A.Id = B.TabaleAId
WHERE B.Column IS NULL
)
Delete From A
答案 3 :(得分:5)
DELETE FROM TableA
LEFT OUTER JOIN TableB
WHERE TableB.Column IS NULL
将删除tableA中没有TableB中相应记录的记录。这就像你追求的那样吗?
答案 4 :(得分:5)
DELETE FROM a
FROM TableA AS a LEFT OUTER JOIN TableB AS b
on a.CALENDAR_DATE = b.CALENDAR_DATE AND a.ID = b.ID
Where b.ID is null
您可以先使用select语句并验证要删除的记录,然后删除select语句并使用上述查询语法添加Delete FROM tablename。
答案 5 :(得分:2)
基于联接删除的最简单方法如下:
1.使用SELECT
语句而不是DELETE
语句
SELECT COLUMNS
FROM Table1
INNER JOIN Table2 ON Table1.YYY = Table2.XXX
2.用SELECT
DELETE FROM TABLE
列
DELETE FROM Table1
FROM Table1
INNER JOIN Table2 ON Table1.YYY = Table2.XXX
请注意,我们需要指定FROM
两次,一个用于DELETE
部分,一个用于JOIN
部分。
答案 6 :(得分:1)
delete from TableA
where id in
(
select id from TableA
except select id from TableB
)
这意味着“从tableA中删除表a中的id而不是表b中的id
否则Merge语句可能对您有帮助(匹配/不匹配时删除等) http://technet.microsoft.com/en-us/library/bb510625.aspx