使用内部连接删除PostgreSQL

vcudknz3  于 2023-02-12  发布在  PostgreSQL
关注(0)|答案(6)|浏览(137)
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_...

我的查询有什么问题?

bqujaahr

bqujaahr1#

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');
dfddblmv

dfddblmv2#

这对我很有效:

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');
sauutmhj

sauutmhj3#

如果有多个联接,可以使用逗号分隔的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'

Reference

7vhp5slm

7vhp5slm4#

另一种与Postgres 9.1+一起工作的形式是将Common Table Expression与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';
g2ieeal7

g2ieeal75#

只需将子查询与INNER JOIN、LEFT JOIN或smth else一起使用:

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'
)

为了优化查询,

mepcadol

mepcadol6#

基本上这里提到的所有东西都在文档中提到了,但是没有人具体说明是什么。所以这就是 * current(v15)* DELETE文档所说的:

注解

PostgreSQL允许你通过在USING子句中指定其他表来引用WHERE条件中的其他表的列。例如,要删除给定制片人制作的所有电影,可以执行以下操作:

DELETE FROM films USING producers
 WHERE producer_id = producers.id AND producers.name = 'foo';

这里实际上发生的是films和producer之间的连接,所有成功连接的films行都被标记为删除。此语法不是标准的。更标准的方法是:

DELETE FROM films
 WHERE producer_id IN (SELECT id FROM producers WHERE name = 'foo');

在某些情况下,关联样式比子选择样式更易于编写或执行。

相关问题