CREATE TABLE table1(id int, name varchar(10), parent_id int)
INSERT table1 VALUES
(1, ‘Home’, 0),
(2, ‘About’, 1),
(3, ‘Contact’, 1),
(4, ‘Legal’, 2),
(5, ‘Privacy’, 4),
(6, ‘Products’, 1),
(7, ‘Support’, 2)
查询 id = 5 的所有父级
SELECT ID.level, DATA.* FROM(
SELECT
@id as _id,
( SELECT @id := parent_id
FROM table1
WHERE id = @id
) as _pid,
当然这种结构就不要追求什么效率了。如果要效率高的,只能改表结构。1:select p2.id from table p1 ,table p2 where p1.id=p2.pid and p1.id=0
2:假设表名是tree
SQL codeselect distinct a.id from tree as a inner join tree as b on (a.pid = b.pid) where b.pid >=0
select distinct a.id from tree as a inner join tree as b on (a.pid = b.pid) where b.pid >=2
3.通过程序或数据库的store procedure来实现了。 在mySQL中无法以一句SQL实现。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)