假设我们有这些表格:
product_id
product_name
category_id
category_name
product_in_category_id
product_id
category_id
如何获得product_in_category表中不属于特定类别的所有产品(无重复项)。
换句话说,例如,所有未分配到类别10的产品。 此外,如果一个产品属于类别1,5和10,则不应该出现结果。
答案 0 :(得分:4)
SELECT p.*
FROM PRODUCT p
LEFT JOIN PRODUCT_IN_CATEGORY pic ON pic.product_id = p.product_id
AND pic.category_id = 10
WHERE pic.product_in_category_id IS NULL
SELECT p.*
FROM PRODUCT p
WHERE p.product_id NOT IN (SELECT pic.product_id
FROM PRODUCT_IN_CATEGORY pic
WHERE pic.category_id = 10)
SELECT p.*
FROM PRODUCT p
WHERE NOT EXISTS (SELECT NULL
FROM PRODUCT_IN_CATEGORY pic
WHERE pic.product_id = p.product_id
AND pic.category_id = 10)
这取决于被比较的列是否可以为空(值可以为NULL)。如果他们是nullable, then NOT IN/NOT EXISTS are more efficient。如果列为not nullable, then LEFT JOIN/IS NULL is more efficient (MySQL only)。
答案 1 :(得分:0)
SELECT * FROM product_in_category WHERE category_id!=10
或者我错过了什么?我想我错过了没有重复的部分,看看InSane更好的答案。
答案 2 :(得分:0)
SELECT product_id FROM product
LEFT OUTER JOIN product_in_category
ON product.product_id = product_in_category.product_id
WHERE product_in_category.product_id IS NULL
GROUP BY product_id