我正在创建一个简单的博客系统,其中帖子可以有多个类别,所以我有这个查询:
SELECT *, GROUP_CONCAT(item_category) AS item_categories
FROM (`dev_pages`)
LEFT JOIN `dev_items_to_categories` ON `dev_items_to_categories`.`item_id` = `dev_pages`.`page_id`
WHERE deleted_time IS NULL
AND `page_type` = 'blog'
AND `item_category` = '16'
ORDER BY `page_title` ASC
它工作正常,但如果没有结果而不是返回任何内容它返回NULL或默认值(请参阅SQL小提琴)
我设法绕过但我想知道是否有人有更好的解决方案:
SELECT a.* FROM (
SELECT *, GROUP_CONCAT(item_category) AS item_categories
FROM (`dev_pages`)
LEFT JOIN `dev_items_to_categories` ON `dev_items_to_categories`.`item_id` = `dev_pages`.`page_id`
WHERE deleted_time IS NULL
AND `page_type` = 'blog'
AND `item_category` = '16'
ORDER BY `page_title` ASC
) AS a
WHERE page_id > 0
答案 0 :(得分:2)
您需要GROUP BY
子句:
SELECT *, GROUP_CONCAT(item_category) AS item_categories
FROM (`dev_pages`)
LEFT JOIN `dev_items_to_categories` ON `dev_items_to_categories`.`item_id` = `dev_pages`.`page_id` AND `item_category` = '16'
WHERE deleted_time IS NULL
AND `page_type` = 'blog'
GROUP BY dev_pages.page_id
ORDER BY `page_title` ASC
您还需要将item_category = '16'
放入ON
子句中。否则,您将在dev_items_to_categories
中过滤掉没有匹配项的行;由于您使用LEFT JOIN
而不是INNER JOIN
,我假设您希望这些行具有空匹配。
答案 1 :(得分:0)
你也可以尝试合并功能。
SELECT *, GROUP_CONCAT(coalece(item_category,'')) AS item_categories
FROM (`dev_pages`)
LEFT JOIN `dev_items_to_categories` ON `dev_items_to_categories`.`item_id` = `dev_pages`.`page_id`
WHERE deleted_time IS NULL
AND `page_type` = 'blog'
AND `item_category` = '16'
ORDER BY `page_title` ASC