首页 > 解决方案 > 搜索不存在属性的产品 ID

问题描述

我正在将 opencart 用于在线商店,并且我有一个这样的 SQL 结构:( 数据 来自 phpmyadmin 的图片)

我正在尝试将产品 ID 与属性 ID 交叉匹配。我需要找到没有特定attribute_id(更准确地说是attribute_id 17)的产品。

我尝试以各种格式排序和导出,但没有成功。我不擅长 mysql 语法,但我确信必须有一种方法来实现这个结果。

还尝试使用此代码:

SELECT product_id FROM oc_product_attribute WHERE NOT EXISTS (SELECT * FROM oc_product_attribute WHERE attribute_id = 17) (oc_product_attribute 是表名)

...但它没有输出任何结果。

请帮助我了解如何找到没有属性 ID 17 的产品 ID。

谢谢!

标签: mysqlphpmyadminopencart

解决方案


你应该有一张product桌子(在你的情况下可能oc_product)。使用它来避免多次检查。也可能存在没有属性的产品。如果您只使用属性表,您会在结果中错过该产品。

有两种常见的方法可以实现您的目标。一种是使用 LEFT JOIN:

select p.*
from oc_product p
left join oc_product_attribute a
  on  a.product_id = p.product_id
  and a.attribute_id = 17
where a.product_id is null

条件a.attribute_id = 17在 ON 子句中很重要。如果在 WHERE 子句中使用它,则 LEFT JOIN 将转换为 INNER JOIN,并且您将得到一个空结果。

另一种方法是使用相关的 NOT EXISTS 子查询:

select p.*
from oc_product p
where not exists (
    select *
    from oc_product_attribute a
    where a.product_id = p.product_id
      and a.attribute_id = 17
)

注意(相关)条件a.product_id = p.product_id。如果你错过了它(就像你的尝试一样),子查询总是会找到一行,而 NOT EXISTS 总是会返回 FALSE。

两种方法具有相似的性能。

如果您只需要产品 ID,则可以替换p.*p.product_id.


推荐阅读