php - 如何从多对多mysql关系中选择唯一值
问题描述
嗨,我对这个 sql 案例感到困惑。我正在使用mysql Ver 15.1 Distrib 10.2.31-MariaDB
. 假设我有 3 个表products
, categories
, 和product_categories
作为数据透视表。
这是数据示例:
products:
| id | name |
------------------------
| 1 | asd wef |
| 2 | gggg2222 |
| 3 | pppga 99 |
| 4 | lalala 55 |
对于类别:
| id | level | parent_id | name |
-----------------------------------
| 20 | 1 | | Fashion |
| 22 | 2 | 20 | Top |
| 23 | 3 | 22 | T-Shirt |
| 24 | 3 | 22 | Jacket |
对于数据透视表,product_categories:
| product_id | category_id |
--------------------------------
| 1 | 20 |
| 1 | 22 |
| 1 | 23 |
| 2 | 22 |
| 2 | 20 |
| 3 | 20 |
| 4 | 20 |
因此,您可以从数据透视表中看到,仅product_id = 3 & 4
在类别级别 1 中停止。并且product_id = 2
仅在类别级别 2 中停止。
我想在这里实现的是当我从categories
表中选择时。我可以数出有多少产品停在这里。这是我想要获取的数据的示例。
"categories": [
{
"id": 20,
"total_product": 4
"stopped_product": 2
},
{
"id": 22,
"total_product": 3
"stopped_product": 1
}
]
到目前为止,我尝试使用group by
:
SELECT * FROM product_categories WHERE product_id IN (1, 2, 3, 4) GROUP BY product_id HAVING category_id=20
输出:
| product_id | category_id |
--------------------------------
| 1 | 20 |
| 3 | 20 |
| 4 | 20 |
预期产出
| product_id | category_id |
--------------------------------
| 3 | 20 |
| 4 | 20 |
解决方案
我猜你只想要最大值
SELECT product_id,MAX(category_id) as category_id FROM product_categories WHERE product_id IN (1, 2,
3, 4)
GROUP BY product_id
HAVING category_id=20
推荐阅读
- html - 始终将 div 放在容器的左侧
- ios - 调试和发布中的不同 URL -iOS
- java - 不可点击的元素
- python - 按值过滤相同类型的DataFrame
- windows - power-shell脚本的windows调度不可靠
- javascript - 正则表达式删除所有以特殊字符开头的字符串
- unity3d - 播放按钮在 UNITY 中不起作用(相机无法启动)[错误:在播放模式下暂停烘烤]
- python-2.x - 用python2做英语到猪拉丁,用字母转换单词到猪拉丁,如何修改它以添加数字和特殊字符
- typescript - 交叉口没有正确缩小联合
- python - 带 GPS 的 Ramer-Douglas-Peucker 算法