编辑加入SQL小提琴东西
SQL Fiddle
的MySQL 5.5.28架构设置:
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`label` varchar(20) NOT NULL,
`level` int(11) NOT NULL,
`path` varchar(100) NOT NULL,
`sortorder` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `category`
--
INSERT INTO `category` (`id`, `parent_id`, `label`, `level`, `path`, `sortorder`) VALUES
(0, 0, '', 0, '', 0),
(2, 0, 'Computer', 1, '.2.', 2),
(3, 0, 'Electronic', 1, '.3.', 1),
(4, 3, 'TV', 2, '.3.4.', 3),
(5, 2, 'Laptop', 2, '.2.5.', 4),
(6, 7, 'LED LCD', 4, '.3.4.7.6.', 5),
(7, 4, 'LCD', 3, '.3.4.7', 5);
查询1:
SELECT
(
SELECT group_concat(cast(g.sortorder AS char) ORDER BY g.path) AS gso
FROM category AS g
WHERE c.path LIKE concat(g.path, '%')
) AS grsortorder, c. *
FROM `category` AS c
ORDER BY grsortorder
Results:
| GRSORTORDER | ID | PARENT_ID | LABEL | LEVEL | PATH | SORTORDER |
-----------------------------------------------------------------------------
| 0 | 0 | 0 | | 0 | | 0 |
| 0,1 | 3 | 0 | Electronic | 1 | .3. | 1 |
| 0,1,3 | 4 | 3 | TV | 2 | .3.4. | 3 |
| 0,1,3,5 | 7 | 4 | LCD | 3 | .3.4.7 | 5 |
| 0,1,3,5,5 | 6 | 7 | LED LCD | 4 | .3.4.7.6. | 5 |
| 0,2 | 2 | 0 | Computer | 1 | .2. | 2 |
| 0,2,4 | 5 | 2 | Laptop | 2 | .2.5. | 4 |
感谢您answer.I添加您的查询的结果你的答案。这是不是导致我需要 – 2013-02-20 14:11:44
这是可能的CONNECT BY来解决,但可惜的是MySQL不提供该条款的支持。看看有没有什么博客文章可以帮助你:http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/ – 2013-02-20 14:32:26
蒂亚戈·塞萨尔·奥利维拉我想明白这一点,但它似乎并没有解决我的问题。 ..我不能采用我的问题 – 2013-02-20 14:45:51