搜索不存在属性的产品 ID
Search for product ids where an attribute is not present
我在网上商店使用 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 是 table 名称)
...但是没有输出任何结果。
请帮助我了解如何找到没有属性 ID 17 的产品 ID。
谢谢!
您当前的方法是正确的,但您需要将存在的子查询与外部查询相关联:
SELECT DISTINCT o1.product_id
FROM oc_product_attribute o1
WHERE NOT EXISTS (SELECT 1 FROM oc_product_attribute o2
WHERE o1.product_id = o2.product_id AND o2.attribute_id = 17);
我们也可以在这里使用聚合方法:
SELECT product_id
FROM oc_product_attribute
GROUP BY product_id
HAVING COUNT(attribute_id = 17) = 0;
你应该有一个 product
table(你的情况可能是 oc_product
)。使用它来避免多次检查。也可能有没有属性的产品。如果您只使用属性 table.
,您会在结果中错过该产品
有两种常见的方法可以实现您的目标。一种是使用 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 将始终 return FALSE.
两种方法的性能相似。
如果您只需要产品 ID,可以将 p.*
替换为 p.product_id
。
我在网上商店使用 opencart,我有一个 SQL 结构,如下所示:
我正在尝试交叉匹配产品 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 是 table 名称)
...但是没有输出任何结果。
请帮助我了解如何找到没有属性 ID 17 的产品 ID。
谢谢!
您当前的方法是正确的,但您需要将存在的子查询与外部查询相关联:
SELECT DISTINCT o1.product_id
FROM oc_product_attribute o1
WHERE NOT EXISTS (SELECT 1 FROM oc_product_attribute o2
WHERE o1.product_id = o2.product_id AND o2.attribute_id = 17);
我们也可以在这里使用聚合方法:
SELECT product_id
FROM oc_product_attribute
GROUP BY product_id
HAVING COUNT(attribute_id = 17) = 0;
你应该有一个 product
table(你的情况可能是 oc_product
)。使用它来避免多次检查。也可能有没有属性的产品。如果您只使用属性 table.
有两种常见的方法可以实现您的目标。一种是使用 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 将始终 return FALSE.
两种方法的性能相似。
如果您只需要产品 ID,可以将 p.*
替换为 p.product_id
。