这是我的分类表
category_id | parent_id
____________________________
27 | 25
28 | 27
29 | 25
26 | 28
25 | 0
30 | 0
31 | 26
..........
..........
我想要显示这样的记录。
category_id | parent_id
____________________________
25 | 0
27 | 25
28 | 27
26 | 28
31 | 26
29 | 25
30 | 0
..........
..........
我看过很多帖子,但我找不到任何东西。 请让我知道查询我的类别表。谢谢。 这是我已经看过的一些链接。 1: enter link description here 2:enter link description here
答案 0 :(得分:0)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(category_id INT NOT NULL
,parent_id INT NULL
);
INSERT INTO my_table VALUES
(27,25),
(28,27),
(29,25),
(26,28),
(25,NULL),
(30,NULL),
(31,26);
SELECT DISTINCT t1.*
FROM my_table t1
LEFT
JOIN my_table t2
ON t2.parent_id = t1.category_id
LEFT
JOIN my_table t3
ON t3.parent_id = t2.category_id
LEFT
JOIN my_table t4
ON t4.parent_id = t3.category_id
ORDER
BY t4.parent_id DESC
, t3.parent_id DESC
, t2.parent_id DESC
, t1.parent_id DESC;
+-------------+-----------+
| category_id | parent_id |
+-------------+-----------+
| 25 | NULL |
| 27 | 25 |
| 28 | 27 |
| 26 | 28 |
| 31 | 26 |
| 29 | 25 |
| 30 | NULL |
+-------------+-----------+
或类似的东西。
因为MySQL还没有对递归†的原生支持,所以这变得有点令人满意,因此备选模型的普及,例如嵌套集 ...
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(category_id INT NOT NULL
,lft INT NOT NULL
,rgt INT NOT NULL
);
INSERT INTO my_table VALUES
(0,1,16),
(25,2,13),
(27,3,10),
(28,4,9),
(26,5,8),
(31,6,7),
(29,11,12),
(30,14,15);
SELECT * FROM my_table ORDER BY lft;
+-------------+-----+-----+
| category_id | lft | rgt |
+-------------+-----+-----+
| 0 | 1 | 16 |
| 25 | 2 | 13 |
| 27 | 3 | 10 |
| 28 | 4 | 9 |
| 26 | 5 | 8 |
| 31 | 6 | 7 |
| 29 | 11 | 12 |
| 30 | 14 | 15 |
+-------------+-----+-----+
† MySQL 8.0将添加对recursive CTE syntax的支持。