有一种表类型:
CREATE TABLE categories
(`id` int, `pid` int, `name` varchar(35),
PRIMARY KEY (id)
)
;
INSERT INTO categories
(`id`, `pid`, `name`)
VALUES
(1, 0, 'a1'),
(2, 0, 'a2'),
(3, 0, 'a3'),
(4, 0, 'a4'),
(5, 0, 'a5'),
(6, 3, 'a6'),
(7, 3, 'a7'),
(8, 5, 'a8'),
(9, 5, 'a9')
;
其中: id - 类别的标识符, pid 是父类别的标识符, 名称 - 类别的名称。
如何编写查询,以便像这样:
| id | path |
|-------------|--------------------------------|
| 1 | a1 |
| 2 | a2 |
| 3 | a3 |
| 4 | a4 |
| 5 | a5 |
| 6 | a3 > a6 |
| 7 | a3 > a7 |
| 8 | a5 > a8 |
| 9 | a5 > a9 |
不可能有多项投资。
答案 0 :(得分:1)
请参阅JOINS上的文档
您可以使用joins
来获得结果。
<强>示例强>:
mysql> SELECT c.id AS child_id
-> , c.name AS child_name
-> , c.pid AS parent_id
-> , p.name AS parent_name
-> , IF( c.pid, CONCAT( p.name, ' > ', c.NAME ), c.NAME ) AS path
-> FROM categories AS c
-> LEFT JOIN categories AS p ON c.pid = p.id
-> ORDER BY child_id;
+----------+------------+-----------+-------------+---------+
| child_id | child_name | parent_id | parent_name | path |
+----------+------------+-----------+-------------+---------+
| 1 | a1 | 0 | NULL | a1 |
| 2 | a2 | 0 | NULL | a2 |
| 3 | a3 | 0 | NULL | a3 |
| 4 | a4 | 0 | NULL | a4 |
| 5 | a5 | 0 | NULL | a5 |
| 6 | a6 | 3 | a3 | a3 > a6 |
| 7 | a7 | 3 | a3 | a3 > a7 |
| 8 | a8 | 5 | a5 | a5 > a8 |
| 9 | a9 | 5 | a5 | a5 > a9 |
+----------+------------+-----------+-------------+---------+
9 rows in set (0.00 sec)
注意强>:
父 - 子树可以更长。
在这种情况下,您最好依赖存储过程或仅将树限制在某个级别。
答案 1 :(得分:1)
Sql server:
select a.id,
case when b.id is null then concat('a',a.name)
else concat('a',b.name,' > ','a',a.name) end as path
from categories a
left outer join
(
select id,pid,name from categories
where id in (select pid from categories)) as b
on a.pid=b.id
此致
Saravanan