MySQL:选择连接行,其中 children 不属于特定的 parents id
MySQL: selecting joined rows, where children don't belong to a specific parents id
这个问题听起来有点混乱,我会尽力解释。我有 4 tables:
- store_item:产品
- store_cat:产品类别。每个产品有 1 个类别。
- store_cat_attribute:类别属性。每个类别都有 N 个属性。
- store_item_stock:按属性分类的产品库存
objective是从store_item_stock
table中获取所有id
个特定产品,如只要 store_item_stock.id_attribute
未 链接到当前 store_item.id_cat
这是结构的 SQLfiddle:http://sqlfiddle.com/#!9/d686b9/2
我当前的查询实际上获取了产品的所有 store_item_stock
行,但它还包括属于当前 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_attribute
2、3&4属于id_cat
2,而id_attribute
33&34属于id_cat
4,那么如果查询的目的要获得所有 store_item_stock
行,除了那些 id_attribute
链接到 store_item.id_cat
2 的行,它应该 return:
- id: 104, id_attribute: 33, stock: 26
- id: 105, id_attribute: 34, stock: 28
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);
我不认为它这么简单,但让我们试试这个,看看条件是否符合您想要的输出。
这个问题听起来有点混乱,我会尽力解释。我有 4 tables:
- store_item:产品
- store_cat:产品类别。每个产品有 1 个类别。
- store_cat_attribute:类别属性。每个类别都有 N 个属性。
- store_item_stock:按属性分类的产品库存
objective是从store_item_stock
table中获取所有id
个特定产品,如只要 store_item_stock.id_attribute
未 链接到当前 store_item.id_cat
这是结构的 SQLfiddle:http://sqlfiddle.com/#!9/d686b9/2
我当前的查询实际上获取了产品的所有 store_item_stock
行,但它还包括属于当前 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_attribute
2、3&4属于id_cat
2,而id_attribute
33&34属于id_cat
4,那么如果查询的目的要获得所有 store_item_stock
行,除了那些 id_attribute
链接到 store_item.id_cat
2 的行,它应该 return:
- id: 104, id_attribute: 33, stock: 26
- id: 105, id_attribute: 34, stock: 28
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);
我不认为它这么简单,但让我们试试这个,看看条件是否符合您想要的输出。