我有如下的
sql server表结构:
ID Name ParentID
-----------------------
1 Root NULL
2 Business 1
3 Finance 1
4 Stock 3
我想在我的网页中显示详细信息
ID Name ParentName
-------------------------
1 Root -
2 Business Root
3 Finance Root
4 Stock Finance
如何构建我的SQL查询?请帮我.
试试这个…
SELECT a.ID,a.Name,b.Name AS 'ParentName'
FROM TABLE AS a LEFT JOIN TABLE AS b on a.ParentID = b.ID
使用左连接,查询将找不到要为NULL加入的任何内容,并为ParentName列返回空白.
编辑:
如果您不希望“父级”列为空,但希望显示“ – ”破折号,请使用此查询.
SELECT a.ID,COALESCE(b.Name,'-') AS 'ParentName'
FROM TABLE AS a LEFT JOIN TABLE AS b on a.ParentID = b.ID