使用INNER JOIN从两个表中获取值时,列名无效

时间:2012-11-08 15:17:02

标签: sql-server tsql join inner-join

我有两张桌子:

tbl_profiles_and_users:

[id] [int] IDENTITY(1,1) NOT NULL,
[profile_id] [int] NOT NULL,
[user_id] [nvarchar](50) NULL

tbl_profiles_and_activities:

[id] [int] IDENTITY(1,1) NOT NULL,
[profile_id] [int] NOT NULL,
[user_id] [nvarchar](50) NOT NULL,
[activity_name] [nvarchar](50) NULL,
[check] [int] NULL,
[preferred] [int] NULL

两个表中都有条目,我试图仅从指定的配置文件中选择用户和活动。

我正在尝试使用以下连接执行此操作:

use [dbName]

SELECT p1.user_id AS User_ID, [p2.activity_name] as [Activity_Name]
FROM tbl_profiles_and_users AS p1 
INNER JOIN tbl_profiles_and_activities AS p2 
ON p1.user_id = p2.user_id AND p1.profile_id = p2.profile_id

但我收到了这条消息 列名称'p2.activity_name'无效 我究竟做错了什么?我可以通过加入获得所需的结果吗?

1 个答案:

答案 0 :(得分:6)

因为您要转义整个列,因此服务器将其作为整个列名称[p2.activity_name]读取,这与[p2].[activity_name]非常不同

SELECT p1.user_id AS User_ID, [p2].[activity_name] as [Activity_Name]
FROM ....