如何从表中获取数据

时间:2010-11-19 08:57:24

标签: sql-server sql-server-2005

我必须从下面提到的表格结构中选择玩家名称,队长名称。

表结构如下。

create table #temp(Playerid int,PlayerName varchar(100),CaptainId int)

PlayerId     PlayerName     CaptainId
--------------------------------------
1            Dhoni          NULL
2            Sachin         1
3            Rahul          1

我必须从此表中选择球员姓名及其队长名称。 任何人都可以

4 个答案:

答案 0 :(得分:1)

假设CaptainId在同一个表上引用了PlayerId,您需要以下内容:

select t.PlayerName, t2.PlayerName as CaptainName
from #temp t
left join #temp t2 on t.CaptainId = t2.PlayerId

如果您想要排除没有队长的球员,您可以将其作为内联球。

你可以转换null,当然:

select t.PlayerName, isnull(t2.PlayerName,'None') as CaptainName
from #temp t
left join #temp t2 on t.CaptainId = t2.PlayerId

答案 1 :(得分:1)

您可以使用自联接和表别名。

这样的东西
SELECT p.PlayerName,
 c.PlayerName CaptainName
FROM #temp p LEFT JOIN
 #temp c ON p.CaptainId = c.PlayerId

答案 2 :(得分:1)

有多种方法可以回答这些问题:

select playerName, (select t2.playername from #temp t2 where t2.playerid = t.captainid  ) from #temp t


select t1.playername , t2.playername captain from #temp t1 left join #temp t2 on t1.captainid = t2.playerid

答案 3 :(得分:0)

SELECT PlayerName, CaptainName 
FROM PlayerTable INNER JOIN CaptainTable
ON PlayerTable.CaptainID=CaptainTable.CaptainID
WHERE CaptainName = 'your query'