如何在mysql中获取第二级类别?

wribegjk  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(239)

你好,我想从第二级的categories表中获取记录。查看我的分类表below:-

id  name     parent_id
 1   Women     ROOT
 2   Dress       1
 3   Denim       1
 4   Sweaters    1
 5   Long Dress  2
 6   Short Dress 2

我试过下面的方法code:-

SELECT categories.id,categories.name,categories.parent_id FROM `categories`
join categories c
on c.id = categories.parent_id

我的预期产出是like:-

id  name     parent_id
 2   Dress       1
 3   Denim       1
 4   Sweaters    1

我想获取第二级的记录,即父id是根,其类别id与父id链接的记录。谢谢

exdqitrt

exdqitrt1#

你可以用在

select * from category where parent_id in (
select id from category where parent_id='ROOT'
)
7kqas0il

7kqas0il2#

我们可以尝试单级自连接,条件是左侧是 ROOT 职位:

SELECT c2.id, c2.name, c2.parent_id
FROM categories c1
INNER JOIN categories c2
    ON c2.parent_id = c1.id
WHERE
    c1.parent_id = 'ROOT';

演示

eyh26e7m

eyh26e7m3#

这将起作用:

select b.id,b.name,b.parent_id from categories a,categories b 
where a.id=b.parent_id and a.parent_id='ROOT';

相关问题