MySQL 2级菜单查询

时间:2009-10-18 18:05:01

标签: sql mysql menu

我正在尝试执行MySQL请求来检索2级菜单(父级和子级)......

当然只有一张桌子:

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

我正在寻找那些结果:

titleCat | titleSubCat | idCategory

cat1     | sub-cat1    | 1
cat1     | sub-cat2    | 1
cat2     | sub-cat3    | 4
cat2     | sub-cat4    | 4
cat3     | NULL        | 7

或类似的东西也可以:

cat1     | null        | 1
cat1     | sub-cat1    | 1
cat1     | sub-cat2    | 1
etc..

我尝试了类似的东西:

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

行不通,但我很难尝试订购记录......

如果您想尝试,可以使用SQL Dump:

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

谢谢! :)

1 个答案:

答案 0 :(得分:1)

您的查询几乎是正确的,但如果您想要没有子类别的类别,则需要使用LEFT JOIN,并且您应该只选择第一个表中的第一级类别。

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