如何在 JOIN 上使用 SELECT 编写 SQL DELETE 语句

How to write a SQL DELETE statement using a SELECT on a JOIN

早上好,我正在尝试 运行 以下脚本,但是我收到 "ORA-00933 SQL Command not properly ended" 错误 谁能看到我哪里出错了:

delete tableA 
FROM tableA 
JOIN tableB
ON tableB.usi = tableA.usi
WHERE tableB.usc = 'ABC'
AND tableA.cfs = '01.01.2013'

感谢观看!

Oracle 不支持 DELETE 语句的 JOIN。您需要使用子查询

delete from tableA 
where exists (select *
              from tableb
              where tableB.usi = tableA.usi
              and tableB.usc = 'ABC'
              AND tableA.cfs = '01.01.2013');

DELETE 语句的完整语法记录在手册中
https://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_8005.htm#SQLRF01505


请注意,如果 tableA.cfsDATE(或 TIMESTAMP)列,则不应依赖隐式数据类型转换。 '01.01.2013' 是字符串文字而不是日期。 Oracle 将 尝试 将其转换为日期,但这可能会失败,具体取决于 SQL 客户端的 NLS 设置。最好使用明确的 ansi 日期文字:where cfs = DATE '2013-01-01' 或使用 to_date() 函数:where cfs = to_date('01.01.2013', 'dd.mm.yyyy').

此外,Oracle 的 DATE 列包含一个时间。因此,除非 csf 列中的所有日期都有时间 00:00:00,否则该条件很可能不匹配任何内容。使用 trunc(tablea.csf) = ... 到 "remove" 日期列的时间部分更安全(它并没有真正删除它,它只是将它设置为 00:00:00

您可以尝试类似的方法:

delete tableA
    WHERE id IN (
       SELECT a.id
       FROM tableA a
       JOIN tableB b
       ON b.usi = a.usi
       WHERE b.usc = 'ABC'
       AND a.cfs = '01.01.2013')