mysql - MySQL:选择连接的行,其中孩子不属于特定的父母 ID
问题描述
这个问题可能听起来有点混乱,我会尽力解释它。我有 4 张桌子:
- store_item : 产品
- store_cat:产品类别。每个产品有 1 个类别。
- store_cat_attribute:类别属性。每个类别有 N 个属性。
- store_item_stock:按属性的产品库存
目标是从表中获取特定产品的所有id
s ,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_attribute
2、3 和 4 属于2,33id_cat
和id_attribute
34 属于id_cat
4,因此如果查询的目的是获取除链接到2 的store_item_stock
行之外的所有行,它应该返回:id_attribute
store_item.id_cat
- id:104,id_attribute:33,库存:26
- id:105,id_attribute:34,库存: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);
我不认为它这么简单,但让我们试试这个,看看条件是否符合你想要的输出。
推荐阅读
- linux - 在小时:分钟:[毫秒]内执行 crontab linux
- javascript - 为 donut chart.js 的标签徽章添加百分比
- docker - Docker Windows 安装失败/库未注册 [Windows 10 Pro]
- flutter - 显示 alertDialog 时 Flutter 键盘消失
- python - 如何以优雅的功能将 pandas DataFrames 导出到 Excel 文件?
- c# - 如何根据输入参数从 c# 动态创建 powershell 脚本,而机器中没有物理脚本文件
- maven - 使用 Maven 运行 java 项目时出现 Stripe.apiKey 错误
- python - 从两个下拉菜单中选择后显示输出
- gradle - Gradle:使用兄弟子项目作为插件
- javascript - 在 React/Redux 中未触发操作