duanbi3385 2013-11-14 11:58 采纳率: 100%
浏览 30

嵌套集模型MySQL

I have to two tables category and category_description. With columns

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

After insert into category table get the last category_id and insert it to category_description table. My Question is how i can select category with parnet and child name and display like this

if category has a child it should display this " parent_name > child_name " if not should display this " parent_name "

  • 写回答

1条回答 默认 最新

  • doujian1954 2013-11-14 14:00
    关注

    Run this (it assumes the parent categories have a NULL in their parent_id column):

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分