1

SQL 小提琴在这里

我正在制作一个简单的博客系统,其中帖子可以有多个类别,所以我有这个查询:

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 Fiddle)

我设法解决了问题,但我想知道是否有人对此有更好的解决方案:

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 
4

2 回答 2

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,我假设您想要那些具有空匹配的行。

小提琴

于 2013-11-11T15:55:50.210 回答
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
于 2013-11-11T15:51:02.897 回答