嵌套集模型MySQL

时间:2013-11-14 11:58:18

标签: php mysql sql

我有两个表类别和category_description。列

`category` (
  `category_id`,
  `image` ,
  `parent_id` ,
  `sort_order`,
  `status` ,
  `created`,
  `modified`,
  PRIMARY KEY (`category_id`)
)

`category_description` (
  `category_id`,
  `name` ,
  `description`,
  `meta_description`,
  `seo_keyword`,
  PRIMARY KEY (`category_id`),
  UNIQUE KEY `name` (`name`)
)

插入类别表后获取最后一个category_id并将其插入category_description表。我的问题是我如何选择带有parnet和子名称的类别并显示如下

如果类别有子项,则应显示此“parent_name> child_name” 如果不是应该显示这个“parent_name”

1 个答案:

答案 0 :(得分:0)

运行此命令(假设父类别在其parent_id列中具有NULL):

SELECT CONCAT(parent_description.name, 
              COALESCE(CONCAT(' > ', child_description.name)
                       ,'')
              ) AS display_this
FROM category AS parent
JOIN category_description AS parent_description
  ON parent.category_id = parent_description.category_id
LEFT JOIN category AS child
  ON parent.category_id = child.parent_id
LEFT JOIN category_description AS child_description
  ON child.category_id = child_description.category_id
WHERE parent.parent_id IS NULL