MySQL2级,MySQL 2级MENU查询

I'm trying to do a MySQL request to retreive a 2 level menu (parent and children)...

There's only 1 table, of course :

idCategory | Title | idCategoryParent | DisplayOrder

1 | cat1 | NULL | 1

2 | sub-cat1 | 1 | 1

3 | sub-cat2 | 1 | 2

4 | cat2 | NULL | 2

5 | sub-cat3 | 4 | 1

6 | sub-cat4 | 4 | 2

7 | cat3 | NULL | 3

I'm looking for those results :

titleCat | titleSubCat | idCategory

cat1 | sub-cat1 | 1

cat1 | sub-cat2 | 1

cat2 | sub-cat3 | 4

cat2 | sub-cat4 | 4

cat3 | NULL | 7

OR something like that would be fine too :

cat1 | null | 1

cat1 | sub-cat1 | 1

cat1 | sub-cat2 | 1

etc..

I tried with something like :

SELECT subcat.title as catTitle, cat.title as parentTitle, subcat.idCategory as catIdCategory, subcat.idCategoryParent

FROM `test_category` as cat

RIGHT OUTER JOIN test_category as subcat ON cat.idCategory=subcat.idCategoryParent

Doesn't work bad but I struggle trying to order the records...

Here's the SQL Dump if you want to try it :

--

-- Table structure for table `test_category`

--

CREATE TABLE IF NOT EXISTS `test_category` (

`idCategory` int(11) NOT NULL AUTO_INCREMENT,

`idCategoryParent` int(11) DEFAULT NULL,

`title` varchar(20) NOT NULL,

`order` int(11) NOT NULL,

PRIMARY KEY (`idCategory`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;

--

-- Dumping data for table `test_category`

--

INSERT INTO `test_category` (`idCategory`, `idCategoryParent`, `title`, `order`) VALUES

(1, NULL, 'cat1', 1),

(2, 1, 'sub-cat1', 1),

(3, 1, 'sub-cat2', 2),

(4, NULL, 'cat2', 2),

(5, 4, 'sub-cat3', 1),

(6, 4, 'sub-cat4', 2),

(7, NULL, 'cat3', 3);

Thanks! :)

解决方案

Your query is almost correct, but you need to use LEFT JOIN if you want categories with no subcategories, and you should select only first-level categories from the first table.

SELECT t1.title, t2.title, t1.idCategory

FROM

test_category t1

LEFT JOIN test_category t2 ON t2.idCategoryParent=t1.idCategory

WHERE t1.idCategoryParent IS NULL

ORDER BY t1.DisplayOrder, t2.DisplayOrder

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值