使用LEFT JOIN删除

时间:2013-03-20 11:14:25

标签: sql postgresql join left-join

我想从表中删除取决于引用第一个表的另一个表上存在的数据,但是,我有代码可以工作并显示当我作为SELECT stetement运行它时要删除的值,但是当我改变它以删除它给我错误,我不明白为什么他们在那里。

DELETE leadCustomer.* FROM coursework.leadCustomer LEFT JOIN coursework.flightBooking
ON leadCustomer.customerID = flightBooking.customerID
WHERE leadCustomer.customerID NOT IN (
SELECT customerID FROM (SELECT customerID, status FROM coursework.flightBooking) AS
StatusCount where status IN  ('R','H') GROUP BY customerID
)
AND leadCustomer.customerID = 8;

错误:

ERROR:  syntax error at or near "leadCustomer"
LINE 1: DELETE leadCustomer.* FROM coursework.leadCustomer LEFT JOIN...
               ^

********** Error **********

ERROR: syntax error at or near "leadCustomer"
SQL state: 42601
Character: 8

我正在使用postgres

5 个答案:

答案 0 :(得分:47)

样品。删除表中的记录' A'表格中没有记录' H'

DELETE A FROM ARTICULO_ALMACEN A
LEFT JOIN HISTORICO_UNION H
ON A.COD_ARTICULO = H.COD_ARTICULO
AND A.COD_ALMACEN = H.COD_ARTICULO_ALMACEN
AND A.TPROPIEDAD1 = H.PROPIEDAD1
AND A.TPROPIEDAD2 = H.PROPIEDAD2
AND A.TPROPIEDAD3 = H.PROPIEDAD3
WHERE H.COD_ARTICULO IS NULL

答案 1 :(得分:14)

从我看到的地方,你实际上并不需要联接来执行此操作......

DELETE FROM coursework.leadCustomer 
WHERE leadCustomer.customerID NOT IN (
SELECT distinct customerID FROM coursework.flightBooking  where status IN  ('R','H') 
)
AND leadCustomer.customerID = 8;

它将使用以下客户ID删除leadcustomer中的所有记录: 1)与8不同 2)不在表格预告片中,状态为“R”或“H”

这不是你想要做的吗?

答案 2 :(得分:0)

您需要这样做:

从TableA中删除 ID在哪里  (从表A中选择ID    左外连接tableB b在a.ID = b.ID上    其中b.ID为NULL)

答案 3 :(得分:-4)

.*移除leadCustomer.* 即:

DELETE leadCustomer FROM coursework.leadCustomer LEFT JOIN coursework.flightBooking
ON leadCustomer.customerID = flightBooking.customerID
WHERE leadCustomer.customerID NOT IN (
SELECT customerID FROM (SELECT customerID, status FROM coursework.flightBooking) AS
StatusCount where status IN  ('R','H') GROUP BY customerID
)
AND leadCustomer.customerID = 8;

答案 4 :(得分:-4)

你可以试试这个

 DELETE leadCustomer FROM coursework.leadCustomer lc
 LEFT JOIN coursework.flightBooking fb ON lc.customerID = fb.customerID 
 and status IN  ('R','H')and fb.customer_id is not null
 WHERE  leadCustomer.customerID = 8;