多表如何加入存储过程?

时间:2012-09-10 15:08:47

标签: sql-server stored-procedures join left-join inner-join

我想要muliti表join.it的显示1数据/显示2记录但真的是1个数据/ 1个记录。

select acl.Person_ID as 'CODE'
,pnr.FullName as 'FullName'
,case acl.persontype when 'normal' then 'normal' end as 'Type'
From tbl_aculog acl left join tbl_PerNR pnr On acl.Person_ID=pnr.Person_ID

union

select acl.Person_ID as 'CODE'
,ps.FullName as 'FullName'
,case acl.persontype when 'blacklist' then 'blacklist' end as 'Type'
From tbl_aculog acl left join tbl_Person ps On acl.Person_ID=ps.NPerson_ID

结果:

Person_ID |    FullName |    Type
00010132 |  Stin|         normal
00010132 |  NULL |        NULL
00000579 |  Plom |        normal
00000579 |  NULL |        NULL
00001081 |  Watson |          normal
00001081 |  NULL |        NULL
5211080 |   SOPIT |       blacklist
5211080 |   NULL |        NULL

**字段Person_ID& FullName&类型为NULL VALUE。

我想要结果:

Person_ID |    FullName |    Type
00010132 |  Stin|         normal
00000579 |  Plom |        normal
00001081 |  Watson |          normal
5211080 |   SOPIT |       blacklist

非常感谢你的时间:D

2 个答案:

答案 0 :(得分:0)

要从结果中删除NULL,您需要指定WHERE acl.persontype IS NOT NULL以忽略空'persontype'。

select acl.Person_ID as 'CODE'
,pnr.FullName as 'FullName'
,case acl.persontype when 'normal' then 'normal' end as 'Type'
From tbl_aculog acl left join tbl_PerNR pnr On acl.Person_ID=pnr.Person_ID
WHERE acl.persontype IS NOT NULL

union

select acl.Person_ID as 'CODE'
,ps.FullName as 'FullName'
,case acl.persontype when 'blacklist' then 'blacklist' end as 'Type'
From tbl_aculog acl left join tbl_Person ps On acl.Person_ID=ps.NPerson_ID
WHERE acl.persontype IS NOT NULL

修改1

使用INNER JOIN会删除NULLS

select acl.Person_ID as 'CODE'
,pnr.FullName as 'FullName'
,case acl.persontype when 'normal' then 'normal' end as 'Type'
From tbl_aculog acl inner join tbl_PerNR pnr On acl.Person_ID=pnr.Person_ID

union

select acl.Person_ID as 'CODE'
,ps.FullName as 'FullName'
,case acl.persontype when 'blacklist' then 'blacklist' end as 'Type'
From tbl_aculog acl inner join tbl_Person ps On acl.Person_ID=ps.NPerson_ID

答案 1 :(得分:0)

这不是结果

更多

Result:

Person_ID |    FullName |    Type
00010132 |  Stin|         normal
00010132 |  NULL |        NULL
00000579 |  Plom |        normal
00000579 |  NULL |        NULL
00001081 |  Watson |          normal
00001081 |  NULL |        NULL
5211080 |   SOPIT |       blacklist
5211080 |   NULL |        NULL
NULL | NULL |        NULL
NULL | NULL |        NULL

I want Result:

Person_ID |    FullName |    Type
00010132 |  Stin|         normal
00000579 |  Plom |        normal
00001081 |  Watson |          normal
5211080 |   SOPIT |       blacklist
NULL | NULL |        NULL
NULL | NULL |        NULL

我很抱歉数据有关。

到“njk”代码结果没有NULL VALUE但我希望在不重复值时显示NULL VALUE。

非常感谢你的时间。 :)