当我使用category
时,此SQL仅从表fetchAll()
中提取一行,我知道至少有两行具有相同的信息。有什么想法吗?
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
);
}
答案 0 :(得分: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