首页 > 解决方案 > MySQL:选择连接的行,其中孩子不属于特定的父母 ID

问题描述

这个问题可能听起来有点混乱,我会尽力解释它。我有 4 张桌子:

目标是从表中获取特定产品的所有ids store_item_stock只要store_item_stock.id_attribute不链接到当前store_item.id_cat

这是结构的 SQLfiddle:http ://sqlfiddle.com/#!9/d686b9/2

我当前的查询实际上获取store_item_stock了产品的所有行,但它还包括属于 current 的属性store_item.id_cat

SELECT store_item_stock.id, store_item_stock.id_attribute, store_item_stock.stock
FROM store_item_stock
LEFT JOIN store_item ON store_item.id_item = store_item_stock.id_item
LEFT JOIN store_cat_attribute ON store_cat_attribute.id_cat = store_item.id_cat
WHERE store_item_stock.id_item = 1 AND store_item.id_cat = 2 GROUP BY store_item_stock.id

例如,id_attribute2、3 和 4 属于2,33id_catid_attribute34 属于id_cat4,因此如果查询的目的是获取除链接到2 的store_item_stock行之外的所有行,它应该返回:id_attributestore_item.id_cat

标签: mysqljoinleft-joinright-join

解决方案


SELECT store_item_stock.id, store_item_stock.id_attribute, store_item_stock.stock 
FROM store_item_stock 
JOIN store_cat_attribute 
ON store_item_stock.id_attribute=store_cat_attribute.id_attribute
WHERE id_cat NOT IN (
SELECT store_item.id_cat 
FROM store_item JOIN store_cat_attribute 
ON store_item.id_cat=store_cat_attribute.id_cat 
WHERE store_item.id_cat=2 
GROUP BY store_item.id_cat);

我不认为它这么简单,但让我们试试这个,看看条件是否符合你想要的输出。


推荐阅读