使用连接连接两个或多个表

时间:2013-04-25 05:51:47

标签: sql sql-server-2008 select join

我有两种类型的表,名为组织 OrgLogin。

组织:

ID
Name

OrgLogin:

LoginId
UserName
Password

我想在组织表中使用用户名和密码进行选择查询。所以我使用了Joins。

我的查询是,

select top(55)'Insert into Organizations(Id,Username,Password,Name)values(' + 
       Cast(o.organizationId as varchar(50))+',''' +
        IsNull(''''+ol.UserName+'''', 'NULL')+','+
       isnull(convert(nvarchar(max),HASHBYTES('MD5',ol.Password),1),'NULL')+ ')' 
    FROM Organization AS o 
    left join OrgLogin As ol ON ol.LoginId=o.OrganizationID

我的结果集如下,

Insert into Organizations(Id,CreateDate,Username,Password)values(1,'NULL,NULL)

Insert into Organizations(Id,CreateDate,Username,Password)values(2,'NULL,NULL)

Insert into Organizations(Id,CreateDate,Username,Password)values(3,'NULL,NULL)

Insert into Organizations(Id,CreateDate,Username,Password)values(4,'NULL,NULL)

Insert into Organizations(Id,CreateDate,Username,Password)values(5,''V EX Electronics Systems Pvt.Ltd.Chennai',0xACB3BB721E1EC47C4CB569331ACC4E8E)

Insert into Organizations(Id,CreateDate,Username,Password)values(5,''V EX Electronics Systems Pvt.Ltd.Chennai',0xACB3BB721E1EC47C4CB569331ACC4E8E)

我正在重复看'5'Id。创造了两次。为什么会这样?任何想法?

1 个答案:

答案 0 :(得分:0)

你应该整理单引号(在第一个ISNULL之前)

select top(55)'
    Insert into Organizations(Id,Username,Password,Name)values(' + 
    Cast(o.organizationId as varchar(50))+',' +
    IsNull(''''+ol.UserName+'''', 'NULL')+','+
    isnull(convert(nvarchar(max),HASHBYTES('MD5',ol.Password),1),'NULL')+ ')' 
FROM Organization AS o 
left join OrgLogin As ol ON ol.LoginId=o.OrganizationID

接下来,只要该组织有多个OrgLogin记录,o.id就会重复。