mysql - 搜索不存在属性的产品 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。
谢谢!
解决方案
你应该有一张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
.
推荐阅读
- python-3.x - AttributeError:只能使用带有字符串值的 .str 访问器(cdQA 包)
- python - 为什么在反转链表并处理新链表的头部后出现 NoneType 错误?
- android - 如何创建小部件(我已经有一个可以工作的活动)
- html - (显示更多/显示更少)角度表中只有一个
- vue.js - NuxtJS 服务器未在 Windows 10 上启动
- amazon-web-services - 我无法在免费套餐上创建 Amazon Connect 实例
- wordpress - 本地化 WooCommerce 扩展
- javascript - 使用nodejs编写文件并设置特殊扩展名
- oracle - Oracle PLSQL - 基于非空的更新
- oop - 如果公共属性打破了封装概念,它们为什么存在?