2011-02-01 53 views
0

假設我有一個變量「userid」,我想從aspnet_Membership和aspnet_AccountProfile表中進行選擇。他們都有列用戶標識,我只是想能夠做出如SELECT * FROM aspnet_AccountProfile,aspnet_Membership WHERE UserId = @ UserId這樣的語句,並且它獲得了與BOTH表匹配的用戶標識的記錄。我該怎麼做呢?謝謝!如何使用兩個表中的一個變量從兩個表中提取數據?

回答

2

這就是所謂的一個JOIN

有幾種基本類型的聯接基於正是你想要的數據。這些與集合論/關係代數有關。我將列出最常用的:

INNER JOIN

使用此當你想返回兩個表有一個匹配的用戶ID行的每一個可能的組合。 中的某些行或者表可能無法在內部聯接中返回。

SELECT * FROM aspnet_AccountProfile INNER JOIN aspnet_Membership 
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId 

寫一個INNER JOIN(其中,如果你想了解加入我不會鼓勵)的另一種方法是:

SELECT * FROM aspnet_AccountProfile, aspnet_Membership 
WHERE aspnet_AccountProfile.UserId = aspnet_membership.UserId 

當然,選擇您想要的特定用戶ID,您可以添加關於或者表的條件例如:

AND aspnet_AccountProfile。用戶ID = @UserId

OR

和aspnet_Membership.UserId = @UserId

無論是這兩個將正常工作的內連接。

LEFT OUTER JOIN

使用此當你想從第一個表中查詢返回所有行,每一個地方在第二個表中的用戶ID匹配的第一個組合。第二張表中的某些行(本例中爲Membership)可能根本不會返回。

SELECT * FROM aspnet_AccountProfile LEFT JOIN aspnet_Membership 
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId 

在這種情況下,您必須使用左欄來縮小您的條件,否則它會自動轉換爲INNER JOIN。

WHERE aspnet_AccountProfile.UserId = @UserId

RIGHT OUTER JOIN

這是相當罕見的,因爲作爲一個左外連接它通常可以寫入。它就像一個左外連接,但是關係中第二個表中的所有行將返回而不是第一個。

SELECT * FROM aspnet_AccountProfile RIGHT JOIN aspnet_Membership 
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId 

FULL OUTER JOIN

使用這個,如果你需要涉及與AccountProfile匹配的用戶ID,以在會員中相應的行中的所有行,但還需要了解哪些在要麼行表在另一個表中沒有匹配。

SELECT * FROM aspnet_AccountProfile FULL OUTER JOIN aspnet_Membership 
ON aspnet_AccountProfile.UserId = aspnet_Membership.UserId 

在FULL OUTER JOIN中,僅爲單個用戶獲取結果有點棘手。你必須指定NULL或正確的值在任何表中都可以。

0

嗨,

您可以通過使用

做「SELECT * FROM aspnet_AccountProfile AP,aspnet_Membership m,其中 ap.UserId = m.UserId ANB ap.UserId = @ UserId「

0

您可以通過內部連接完成此操作。

這裏是例子,

Select aspnet_Membership.*, aspnet_AccountProfile.* from aspnet_AccountProfile 
inner join aspnet_Membership on aspnet_Membership.userid = aspnet_AccountProfile.userid 
where [email protected] 

這將只得到whem用戶ID是常見的兩個表中的記錄。

如果你想這是在1個表中的記錄,並可能會或可能不會在其他的則必須用戶的左連接

Select aspnet_Membership.*, aspnet_AccountProfile.* from aspnet_AccountProfile 
left join aspnet_Membership on aspnet_Membership.userid = aspnet_AccountProfile.userid 
where [email protected] 
0

您可以使用加入。

喜歡的東西:

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

謝謝
Vamyip

0

您可以使用一個簡單的內連接這一點。

相關問題