我需要在一个选择查询中显示parent_name [英] I need to display parent_name in one select query
本文介绍了我需要在一个选择查询中显示parent_name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的桌子
this is my table
id | Parent_id | Category
1 | 0 | Clothes
2 | 1 | Women
3 | 2 | Jewellery
4 | 0 | Mobiles
我的尝试:
选择查询我需要显示如下
What I have tried:
by select query i need to display like below
id | Parent_id | Category | Parent_name
1 | 0 | Clothes | none
2 | 1 | Women | Clothes
3 | 2 | Jewellery | Women
4 | 0 | Mobiles | none
推荐答案
检查:
Check this:
DECLARE @hierarchy TABLE (id INT IDENTITY(1,1), Parent_id INT, Category NVARCHAR(50))
INSERT INTO @hierarchy (Parent_id, Category)
VALUES(0, 'Clothes'),
(1, 'Women'),
(2, 'Jewellery'),
(0, 'Mobiles')
SELECT a.id, a.Parent_id, a.Category, ISNULL(b.Category, 'none') As Parent_Name
FROM @hierarchy AS a LEFT JOIN @hierarchy AS b ON a.Parent_id = b.id
我强烈反对建议阅读: SQL连接的可视化表示 [ ^ ]
这篇关于我需要在一个选择查询中显示parent_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文