我有一个这样的表(这个表是我的产品类别):
id title parent_id
1 A 0
2 A1 1
3 A2 1
4 B 0
5 A11 2
6 B1 4
现在,我怎样才能获得最后一个子类别? 例如:
B1
A11
A2
答案 0 :(得分:1)
您似乎想要的行不是另一行的父级:
select pc.*
from productcategories pc
where not exists (select 1
from productcategories pc2
where pc2.parent_id = pc.id
);
答案 1 :(得分:0)
尝试下面的内容;
我的SQL版
SELECT parent_id
,id
,title
FROM
(
SELECT @row_num := IF(@prev_value=p.parent_id,@row_num+1,1) AS RowNumber
,p.parent_id
,p.id
,p.title
,@prev_value := p.parent_id
FROM Product p,
(SELECT @row_num := 1) x,
(SELECT @prev_value := 0) y
ORDER BY p.parent_id,p.id DESC
) subquery
WHERE RowNumber = 1 AND parent_id>0
ORDER BY parent_id DESC
MSSQL版本:
SELECT id,Title,parent_id
FROM ( SELECT id,Title,parent_id,ROW_NUMBER() OVER(PARTITION BY parent_id ORDER BY id DESC) LocalId
FROM [dbo].[Product] ) AS P
WHERE P.LocalId=1
AND parent_id>0
ORDER BY parent_id DESC