有计数的PArent类别

时间:2014-12-22 11:29:53

标签: php mysql

我有一个与查询相关的问题,我有一个类别表,子类别也提到了与其父ID相同的表格。

问题是我需要计算一下父类别中有多少catgeories被添加到父类别中......我如何修改以下查询,它会让我再次计算父类别名称...

以下是我的询问:

SELECT 
P.catName,
P.cID,
P.catParent,
P.catLink,
P.catIcon,
P.catStatus, 
U.catName AS Parent_name 
FROM `dev_web_categories` AS P 
LEFT JOIN `dev_web_categories` AS U ON U.cID = P.catParent

表是:

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以将查询编写为:

SELECT
category.catName AS CategoryName,
(select count(*) from dev_web_categories as subCategory where subCategory.catParent = category.cID) AS TotalSubCategories
FROM dev_web_categories AS category
WHERE category.catParent = 0

答案 1 :(得分:0)

// Create function in mysql 
CREATE DEFINER=`root`@localhost FUNCTION `GetAllNode`(GivenID INT) RETURNS text CHARSET latin1
    DETERMINISTIC
BEGIN
    DECLARE rv,q,queue,queue_children TEXT;
    DECLARE queue_length,front_id,pos INT;
    SET rv = '';
    SET queue = GivenID;
    SET queue_length = 1;
    WHILE queue_length > 0 DO
        SET front_id = FORMAT(queue,0);
        IF queue_length = 1 THEN
            SET queue = '';
        ELSE
            SET pos = LOCATE(',',queue) + 1;
            SET q = SUBSTR(queue,pos);
            SET queue = q;
        END IF;
        SET queue_length = queue_length - 1;
        SELECT IFNULL(qc,'') INTO queue_children
        FROM (SELECT GROUP_CONCAT(CAST(cID AS CHAR(50))) AS qc
        FROM dev_web_categories WHERE `catParent` = front_id) A ;
        IF LENGTH(queue_children) = 0 THEN
            IF LENGTH(queue) = 0 THEN
                SET queue_length = 0;
            END IF;
        ELSE
            IF LENGTH(rv) = 0 THEN
                SET rv = queue_children;
            ELSE
                SET rv = CONCAT(rv,',',queue_children);
            END IF;
            IF LENGTH(queue) = 0 THEN
                SET queue = queue_children;
            ELSE
                SET queue = CONCAT(queue,',',queue_children);
            END IF;
            SET queue_length = LENGTH(queue) - LENGTH(REPLACE(queue,',','')) + 1;
        END IF;
    END WHILE;
    RETURN rv;
END

//使用cID调用函数

SELECT cID,GetAllNode(cID)FROM dev_web_categories