Mysql过滤结果基于另一个表

时间:2014-10-23 16:05:43

标签: mysql

我有一些表,我想从结果中删除另一个表中存在的表。

这是第一个电话,因此您可以看到我正在使用的表格:

    SELECT a.id_product, b.id_product_attribute 
    FROM ps_product_lang a 
    LEFT JOIN ps_product_attribute b 
    ON (a.id_product = b.id_product)

表:

id_product | id_product_attribute
   25              null
   26              null
   27              192
   27              193
   27              194
   27              195

在我的另一张表中,我有这个:

SELECT * FROM eds_combinable_products

id_product  |  id_product_attribute
   25                 null
   27                 194

我试图通过此次调用来过滤我的结果,但对没有产品属性的产品没有运气。它将删除具有属性的那些。

SELECT a.id_product, b.id_product_attribute 
FROM ps_product_lang a 
LEFT JOIN ps_product_attribute b 
ON (a.id_product = b.id_product)
WHERE NOT EXISTS(
      SELECT c.id_product, c.id_product_attribute 
      FROM eds_combinable_products as c
      WHERE a.id_product = c.id_product
                    AND
            b.id_product_attribute = c.id_product_attribute
      )

2 个答案:

答案 0 :(得分:1)

或者,或许更简单:

SELECT  a.id_product, 
        b.id_product_attribute 
FROM    ps_product_lang a LEFT JOIN ps_product_attribute b ON (a.id_product = b.id_product)
        LEFT JOIN eds_combinable_products as c on a.id_product = c.id_product
WHERE   c.id_product_attribute is not null

答案 1 :(得分:0)

我通过向NOT EXISTS调用

添加IF语句来解决这个问题
SELECT a.id_product, b.id_product_attribute FROM ps_product_lang a 
LEFT JOIN ps_product_attribute b ON (a.id_product = b.id_product)
WHERE NOT EXISTS(SELECT c.id_product, c.id_product_attribute FROM eds_combinable_products as c WHERE      a.id_product = c.id_product AND IF(b.id_product_attribute,b.id_product_attribute,0) = c.id_product_attribute)