两个具有相同表的内连接

时间:2014-08-04 05:48:20

标签: sql sql-server inner-join

我有这个问题,我已经工作了一段时间,我只是无法弄清楚我的查询有什么问题。今天,我终于离得更近了,现在我觉得我很接近并且离成功不太远,但是我需要你的帮助才能发现这个问题中的错误,因为我觉得我已经瞎了眼。这是我得到的错误:

“FROM子句中的对象”webpages_UsersInRoles“和”webpages_UsersInRoles“具有相同的公开名称。使用相关名来区分它们。”

SELECT * FROM Users 
INNER JOIN webpages_UsersInRoles 
ON webpages_UsersInRoles.UserId = Users.UserId 
INNER JOIN webpages_UsersInRoles 
ON webpages_UsersInRoles.RoleId = webpages_Roles.RoleId
WHERE Users.UserId = 1

提前谢谢!

3 个答案:

答案 0 :(得分:2)

您必须为表使用别名:

SELECT * FROM Users 
INNER JOIN webpages_UsersInRoles w1 ON w1.webpages_UsersInRoles.UserId = Users.UserId 
INNER JOIN webpages_UsersInRoles w2 ON w1.webpages_UsersInRoles.RoleId = w2.webpages_Roles.RoleId
WHERE Users.UserId = 1

答案 1 :(得分:1)

我认为以下是您需要的最终查询。为了清晰起见,我使用别名TAB1,TAB2 and TAB3来避免混淆。根据需要进行更改。

SELECT * FROM Users TAB1
INNER JOIN webpages_UsersInRoles  TAB2
ON TAB2.UserId = TAB1.UserId 
INNER JOIN webpages_Roles TAB3
ON TAB2.RoleId = TAB3.RoleId
WHERE TAB1.UserId = 1

Btw,JUST FOR INFO ....可能你在原始查询的下面提到的行中出现“The objects "webpages_UsersInRoles" and "webpages_UsersInRoles" in the FROM clause have the same exposed names. Use correlation names to distinguish them.”错误:

SELECT * FROM Users 
INNER JOIN webpages_UsersInRoles 
ON webpages_UsersInRoles.UserId = Users.UserId 
INNER JOIN webpages_UsersInRoles 
ON webpages_UsersInRoles.RoleId  -----> Not able to identify which webpages_UsersInRoles  is being called (First inner join or second inner join)
  = webpages_Roles.RoleId
WHERE Users.UserId = 1

答案 2 :(得分:0)

我看到3个表格Userswebpages_UsersInRoleswebpages_Roles

只有2人被召唤。

webpages_Roles ??

可能在第二次加入中使用webpages_Roles

SELECT * FROM Users 
INNER JOIN webpages_UsersInRoles 
ON webpages_UsersInRoles.UserId = Users.UserId 
INNER JOIN webpages_Roles 
ON webpages_UsersInRoles.RoleId = webpages_Roles.RoleId
WHERE Users.UserId = 1