C# 如何使用两个表都有的一个变量从两个表中提取数据?

C# 如何使用两个表都有的一个变量从两个表中提取数据?,c#,asp.net,sql,C#,Asp.net,Sql,假设我有一个变量“userid”,我想从aspnet_成员和aspnet_AccountProfile表中进行选择。它们都有userid列,我只是希望能够从aspnet_AccountProfile、aspnet_Membership中生成一个类似SELECT*的语句,其中userid=@userid,它将获取两个表中具有匹配用户id的记录。我该怎么做?谢谢大家! 嗨 你可以使用 “从aspnet\u AccountProfile中选择* ap,aspnet_会员资格在哪里 ap.UserId=

假设我有一个变量“userid”,我想从aspnet_成员和aspnet_AccountProfile表中进行选择。它们都有userid列,我只是希望能够从aspnet_AccountProfile、aspnet_Membership中生成一个类似SELECT*的语句,其中userid=@userid,它将获取两个表中具有匹配用户id的记录。我该怎么做?谢谢大家!

你可以使用

“从aspnet\u AccountProfile中选择* ap,aspnet_会员资格在哪里 ap.UserId=m.UserId ANB ap.UserId=@UserId“


您可以通过内部联接来实现这一点

SELECT * FROM aspnet_AccountProfile INNER JOIN aspnet_Membership
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId
举个例子

 Select aspnet_Membership.*, aspnet_AccountProfile.* from aspnet_AccountProfile 
inner join aspnet_Membership on aspnet_Membership.userid = aspnet_AccountProfile.userid 
where aspnet_Membership.UserId=@UserId
当两个表中的userid都是公共的时,这将只获取记录

如果要获取位于1个表中且可能位于或不位于其他表中的记录,则必须使用左联接

就是

 Select aspnet_Membership.*, aspnet_AccountProfile.* from aspnet_AccountProfile 
left join aspnet_Membership on aspnet_Membership.userid = aspnet_AccountProfile.userid 
where aspnet_Membership.UserId=@UserId
您可以使用连接

比如:

Select * from aspnet_AccountProfile INNER JOIN aspnet_Membership
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId
Where aspnet_AccountProfile.UserId = @UserId
谢谢,

Vamyip

您可以为此使用一个简单的内部联接。

它被称为
联接

有几种基本的连接类型,它们取决于您到底需要什么样的数据。这些都与集合论/关系代数有关。我将列出最常见的:

内部联接

如果要返回两个表都有匹配用户标识的所有可能的行组合,请使用此选项。两个表中的某些行可能无法在内部联接中返回

SELECT * FROM aspnet_AccountProfile INNER JOIN aspnet_Membership
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId
编写内部联接的另一种方法(如果您想了解联接,我不鼓励这样做)是:

当然,要选择所需的特定用户ID,可以在任一表上添加一个条件,例如:

和aspnet_AccountProfile.UserId=@UserId

和aspnet_Membership.UserId=@UserId

这两种方法中的任何一种都适用于内部联接

SELECT * FROM aspnet_AccountProfile INNER JOIN aspnet_Membership
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId
左外连接

如果要返回查询中第一个表中的所有行,以及第二个表中的用户标识与第一个表匹配的每个组合,请使用此选项。第二个表中的某些行(在本例中为成员)可能根本无法返回

SELECT * FROM aspnet_AccountProfile LEFT JOIN aspnet_Membership
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId
在这种情况下,必须使用左列缩小条件的范围,否则它将自动转换为内部联接

其中aspnet_AccountProfile.UserId=@UserId

右外连接

这是相当罕见的,因为它通常可以写为左外连接。它类似于左外部联接,但返回关系中第二个表中的所有行,而不是第一个表中的行

SELECT * FROM aspnet_AccountProfile RIGHT JOIN aspnet_Membership
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId
完全外部联接

如果需要将AccountProfile中具有匹配UserId的所有行与Membership中的对应行关联,并且还需要知道其中一个表中的哪些行与另一个表中的行不匹配,请使用此选项

SELECT * FROM aspnet_AccountProfile FULL OUTER JOIN aspnet_Membership
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId
在完全外部联接中,仅为单个用户获取结果有点棘手。您必须在两个表中指定NULL或正确的值