EDITはSQLフィドルのものを追加しました
SQLフィドル
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
結果:
| 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 |