首页 > 解决方案 > 如何从多对多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            |

标签: phpmysqlsql

解决方案


我猜你只想要最大值

    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

推荐阅读