Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 具有产品计数和父类别的SQL产品类别_Mysql_Sql - Fatal编程技术网

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

Mysql 具有产品计数和父类别的SQL产品类别,mysql,sql,Mysql,Sql,我正在尝试编写SQL查询以获取: Category_ID, Category_Name, Category_Parent, Category, ProductCount from two tables Product_Category and Product 我想从查询中获得结果: Category_ID | Category_Name | Category_Parent | ProductCount 所以,我找到了解决问题的办法 SELECT X.id, X

我正在尝试编写SQL查询以获取:

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

我想从查询中获得结果:

Category_ID | Category_Name | Category_Parent | ProductCount 

所以,我找到了解决问题的办法

    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

使用
over
可以在
聚合函数中执行相同的
分组操作

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中的结果: