PostgreSQL用内连接删除

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_... 

我的查询有什么问题?

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

这对我工作:

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

另一种适用于Postgres 9.1+的forms是将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'; 

只需使用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' ) 

优化查询,

  • 使用NOT EXISTS而不是IN
  • 和WITH用于大型子查询