具有产品计数和父类别的 SQL 产品类别

时间:2021-05-06 04:55:55

标签: mysql sql

我正在尝试编写一个 SQL 查询来获取:

Category_ID, Category_Name, Category_Parent, Category, ProductCount 
from two tables Product_Category and Product

Product_Category has columns: id, name, parent_id, status

Product has columns: id, category_id, name

我想从查询中得到结果:

Category_ID | Category_Name | Category_Parent | ProductCount 

2 个答案:

答案 0 :(得分:1)

使用 over,您可以在 group by 中执行相同的 aggregate functions 工作。

SELECT  
    DISTINCT Product_Category.id AS Category_ID,
    Product_Category.name AS Category_Name,
    Product_Category.parent_id AS Category_Parent,
    COUNT(Product.id) OVER (partition  BY Product_Category.id) AS ProductCount
FROM Product JOIN Product_Category ON Product.category_id = Product_Category.id

结果在mysql:https://dbfiddle.uk

答案 1 :(得分:0)

所以,我找到了问题的解决方案。

    SELECT
    X.id,
    X.category,
    X.parent,
    X.status,
    Y.product_count
FROM
    (
    SELECT
        c.id AS id,
        c.name AS Category,
        p.name AS Parent,
        c.status AS
    STATUS
FROM
    product_category c
LEFT JOIN product_category p ON
    c.parent_id = p.id
) X
LEFT JOIN(
    SELECT
        c.id,
        COUNT(p.id) AS product_count
    FROM
        product_category c
    LEFT JOIN product p ON
        c.id = p.category_id
    GROUP BY
        p.category_id
) AS Y
ON
    X.id = Y.id