PostgreSQL通过内部联接删除


197
DELETE B.* 
FROM   m_productprice B  
       INNER JOIN m_product C ON B.m_product_id = C.m_product_id 
WHERE  C.upc = '7094' AND B.m_pricelist_version_id = '1000020'

我收到以下错误PostgreSQL 8.2.11

ERROR:  syntax error at or near "B"
LINE 1: DELETE B.* from m_productprice B  INNER JOIN m_product C ON ...

我尝试给

DELETE B from m_productprice B  INNER JOIN m_product C ON B....
 ERROR:  syntax error at or near "B"

我尝试给

ERROR:  syntax error at or near "INNER"
LINE 1: DELETE from m_productprice B  INNER JOIN m_product C ON B.m_...

我的查询有什么问题?


3
8.2?您应该尽快升级。该版本不再受支持。并请阅读手册:INNER JOINDELETE语句不可用:postgresql.org/docs/8.2/static/sql-delete.html
a_horse_with_no_name 2012年

在没有内部
联接的

参见手册,有一个确切的例子。
a_horse_with_no_name 2012年

Answers:


296
DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

要么

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

@ 0mesh其用于mysql ..我的疑问是用于sql和postgre sql
花花公子

14
对于较大的表,此答案中的第一个解决方案可能要快得多。
mgoldwasser 2014年

2
最佳答案,尤其是第一个答案,因为它允许您按多个字段进行匹配。
Kostanos '17

57

这为我工作:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

31

与Postgres 9.1+配合使用的另一种形式是将通用表表达式与用于联接的USING语句组合在一起。

WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id 
AND B.m_pricelist_version_id = '1000020';

26

如果您有多个联接,则可以使用逗号分隔的USING语句:

DELETE 
FROM 
      AAA AS a 
USING 
      BBB AS b,
      CCC AS c
WHERE 
      a.id = b.id 
  AND a.id = c.id
  AND a.uid = 12345 
  AND c.gid = 's434sd4'

参考


22

只需将子查询与INNER JOIN,LEFT JOIN或其他方式一起使用:

DELETE FROM m_productprice
WHERE m_product_id IN
(
  SELECT B.m_product_id
  FROM   m_productprice  B
    INNER JOIN m_product C 
    ON   B.m_product_id = C.m_product_id
  WHERE  C.upc = '7094' 
  AND    B.m_pricelist_version_id = '1000020'
)

优化查询,

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.