Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

php - left join only fetches one row

This SQL only fetches one row from the table category when I'm using fetchAll(), I know there is atleast two rows with the same info. Any ideas?

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
        );
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have a aggregate function group_concat and without group by clause it will always return one row, you may need to add a group by at the end.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...