MYSQL从子类别中选择

时间:2013-06-30 00:39:39

标签: php mysql parent-child

试图让产品在树下几层......它没有用。

SELECT Products。*                 来自Products

            LEFT JOIN   `Product_Categories` C
                ON  `Products`.`Category_ID` = C.`ID`
                OR  `Products`.`Sub_Category_ID` = C.`ID`
                OR  `Products`.`Sub_Category2_ID` = C.`ID`

            LEFT JOIN   `Product_Categories` C2
                ON      C.`ID` = C2.`Parent_ID`

            LEFT JOIN   `Product_Categories` C3
                ON      C2.`ID` = C3.`Parent_ID`

            LEFT JOIN   `Product_Categories` C4
                ON      C3.`ID` = C4.`Parent_ID`

            LEFT JOIN   `Product_Categories` C5
                ON      C4.`ID` = C5.`Parent_ID`

            LEFT JOIN   `Product_Categories` C6
                ON      C5.`ID` = C6.`Parent_ID`

            WHERE       `Products`.`Is_Master_Product` = 'Yes'
                AND     `Products`.`Is_Published` = 'Yes'
                AND     (`Products`.`Category_ID` = '29'
                        OR      `Products`.`Sub_Category_ID` = '29'
                    OR      `Products`.`Sub_Category2_ID` = '29')
            GROUP BY    `Products`.`Name`
            ORDER BY    `Products`.`Name` ASC

2 个答案:

答案 0 :(得分:0)

SELECT `Products`.*
            FROM        `Products`

            LEFT JOIN   `Product_Categories` C
                ON  `Products`.`Category_ID` = C.`ID`
                OR  `Products`.`Sub_Category_ID` = C.`ID`
                OR  `Products`.`Sub_Category2_ID` = C.`ID`

            LEFT JOIN   `Product_Categories` C2
                ON      C.`ID` = C2.`Parent_ID`

            LEFT JOIN   `Product_Categories` C3
                ON      C2.`ID` = C3.`Parent_ID`

            LEFT JOIN   `Product_Categories` C4
                ON      C3.`ID` = C4.`Parent_ID`

            LEFT JOIN   `Product_Categories` C5
                ON      C4.`ID` = C5.`Parent_ID`

            LEFT JOIN   `Product_Categories` C6
                ON      C5.`ID` = C6.`Parent_ID`

            WHERE       `Products`.`Is_Master_Product` = 'Yes'
                AND     `Products`.`Is_Published` = 'Yes'
                AND     (C.`Parent_ID` = '$category_ID'
                    OR  C.`ID` = '$category_ID')
            GROUP BY    `Products`.`Name`
            ORDER BY    `Products`.`Name` ASC

答案 1 :(得分:-1)

提供表架构,示例数据。 也许存储过程会更好的方法?