[英]Sql server join/subselect question
I have two tables in the database 我的数据库中有两个表
Team:Id(int PK), Name(nvarchar)
and 和
Player:Id(int PK), Name(nvarchar), Age(int), TeamId(int FK)
I also have the following classes 我也有以下课程
class Team
{
public int Id{get;set;}
public string Name{get;set;}
}
and 和
class Player
{
public int Id{get;set;}
public string Name{get;set;}
public int Age{get;set;}
public int TeamId{get;set;}
}
and 和
class TeamInfo
{
public Team Team{get;set;}
public List<Player> Players{get;set;}
}
I want to extract from the databse a List<TeamInfo>
. 我想从数据库中提取List<TeamInfo>
。 I am using Ado.net, no ef or linq2sql... and I am asking what is the best way to query the db? 我正在使用Ado.net,没有ef或linq2sql ...,我在问什么是查询数据库的最佳方法?
Right now I get all teams and for each team I query the table players with a join but for sure it's not the best way. 现在,我得到了所有团队,并且对于每个团队,我都向联接表查询玩家,但是可以肯定的是,这并不是最好的方法。
i'd create an sp in sql server with the parameters @teamid, then execute the sp for the team and get the player info 我会在SQL Server中使用参数@teamid创建一个sp,然后为团队执行sp并获取玩家信息
create procedure [dbo].[TeamPlayers]
as
@teamid int
begin
set nocount on;
select
t.ID as TeamID,
t.name,
p.ID as PlayerID,
p.name,
p.age
from dbo.Player p
inner join Team t
on p.TeamID=t.ID
where t.ID=@teamid
end
you should read all info from database with join
query: 您应该使用join
查询从数据库中读取所有信息:
SELECT
Team.Id as TeamId,
Team.Name as TeamName,
Player.Id as PlayerId,
Player.Name as PlayerId,
FROM Team INNER JOIN Player on Team.Id = Player.TeamId
Use this query as part of SqlCommand
and get data into DataTable
. 将此查询用作SqlCommand
一部分,并将数据获取到DataTable
。 Then: 然后:
var teamInfos = datatable.Rows
.Cast<DataRow>()
.GroupBy(dr => (int) dr["TeamId"])
.Select(t => new TeamInfo
{
Team = new Team{ Id = t.Key,
Name = (string)t.First["TeamName"] },
Players = t.Select(p => new PlayerInfo {
Id = (int)p["PlayerId"],
Name = (int)p["PlayerName"],
// other player fields here
})
.ToList()
});
NOTE: Probably you need a LEFT
join here instead of INNER
since you won't get teams without players otherwise. 注意:您可能需要在这里加入LEFT
,而不是INNER
因为否则您将没有队员进入队伍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.