【问题标题】:left join only fetches one row左连接只取一行
【发布时间】:2015-03-20 09:39:27
【问题描述】:

当我使用fetchAll() 时,此SQL 仅从表category 中获取一行,我知道至少有两行具有相同的信息。有什么想法吗?

Click here to see a more detailed explanation of what I thought the problem was

        $query = "        SELECT        
                                category.*,
                                GROUP_CONCAT('category_hierarchy.category_id' SEPARATOR ',') AS subcategories   

                FROM            category
                LEFT JOIN       category_hierarchy      ON      category.category_id = category_hierarchy.category_parent_id
                WHERE           category.type = '1'
                ORDER BY        category.sort_order ASC";


// Prepare.
    $stmt = $dbh->prepare($query);

// Execute.
    $stmt->execute();

// Fetch results.
    $categories = $stmt->fetchAll();

    $countedRows = count($categories);

    foreach($categories as $category) {
        $parent_arr = '';
        if(!empty($category['subcategories'])) {
            $parent_arr = array(display_children($category['subcategories']));
        } 

        $arr[] = array(
                'category_id'   => $category['category_id'],
                'title'         => $category['title'],
                'slug'          => $category['slug'],
                'url'           => $category['url'],
                'type'          => $category['type'],
                'sort_order'    => $category['sort_order'],
                'categories'    => $parent_arr
        );
    }

【问题讨论】:

    标签: php mysql sql pdo


    【解决方案1】:

    您有一个聚合函数group_concat,并且没有group by 子句,它将始终返回一行,您可能需要在末尾添加group by

    SELECT      
    category.*,
    GROUP_CONCAT('category_hierarchy.category_id' SEPARATOR ',') AS subcategories   
    FROM            category
    LEFT JOIN       category_hierarchy      ON      category.category_id = category_hierarchy.category_parent_id
    WHERE           category.type = '1'
    group by         category.category_id
    ORDER BY        category.sort_order ASC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 2011-01-17
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2013-05-16
      相关资源
      最近更新 更多