0

我在查询 MySQL 时遇到问题。我想实际获取具有 current 值的记录数parent_cat_id。所以在这种情况下,我们需要一个 sub_query 来告诉我们 4(因为有 4

id  parent_cat_id   cat_name                                        
6   2   Carrot                                      
8   2   Potatoes                                        
7   2   Lettuce                                     
13  2   Asparagus                                       
4   1   Pears                                       
3   1   Banannas                                        
2   1   Apples                                      

Main $query 产生我发布的内容以及我将使用的更多信息....

$menu_query = "SELECT c.id AS id, parent_cat_id, cat_name FROM db.category c JOIN db.parent_category pc ON pc.id = c.parent_cat_id WHERE c.is_active = 1 AND c.is_menu = 1 ORDER BY pc.sort_order, c.sort_order;";

$menu_result = mysql_query($menu_query) or die(mysql_error());

while($menu_row = mysql_fetch_array($menu_result)){
    $menu_name = $menu_row['cat_name'];
    $id = $menu_row['id'];
    $parent_cat_id = $menu_row['parent_cat_id'];
            #echo $parent_cat_id;
    #return from database the $count of  records with the same  ['parent_cat_id'] 's

所以我希望有某种形式的 $sub_query 以便我知道在我的 php 代码中构建下一个菜单项。第一个菜单应该有 4 个,第二个菜单应该有 3 个。

谢谢。

更新最终工作子查询

SELECT c.id AS category_id, c.parent_cat_id, cat_name, d.totalCount 
FROM category c 
INNER JOIN parent_category pc 
ON pc.id = c.parent_cat_id 
INNER JOIN(
    SELECT parent_cat_id, COUNT(*) totalCount 
    FROM category 
    WHERE is_menu = 1 
    AND parent_cat_id = 2 
    ORDER BY parent_cat_id 
) d 
ON c.parent_cat_id = d.parent_cat_id 
WHERE c.is_active = 1 
AND c.is_menu = 1 
ORDER BY pc.sort_order, c.sort_order;

再次感谢您的帮助!!!我只需要在你教我的子查询中加入另一个 WHERE 子句。

4

1 回答 1

1

您可以有额外的子查询来计算每个的值parent_cat_id

SELECT  c.id AS id,
        pc.parent_cat_id,
        pc.cat_name,
        d.totalCount
FROM    db.category c
        INNER JOIN db.parent_category pc
            ON pc.id = c.parent_cat_id
        INNER JOIN
        (
            SELECT parent_cat_id, COUNT(*) totalCount
            FROM db.parent_category
            GROUP BY parent_cat_id
        ) d ON c.parent_cat_id = d.parent_cat_id
WHERE   c.is_active = 1 AND 
        c.is_menu = 1
ORDER   BY  pc.sort_order,
            c.sort_order
于 2013-01-04T01:32:32.813 回答