在您提供的示例中,您根本不需要连接。我希望这是一个真实的例子,而不是人为的例子。你想做的很简单,你根本不需要join,也不需要row_number。你可以这样做:
select id,Username,Fullname from Users
UNION ALL
select id,Username,Fullname from GrobUsers
where id not in (select id from Users)
UNION ALL
select id,Username,Fullname from FrobUsers
where id not in (select id from Users) and id not in (select id from GrobUsers)
它会给你这个:
id Username Fullname
----------- ---------- -----------------
7 iboyd Ian Boyd
8 nicholle Nicholle Kuzniak
9 chris Chris Windibank
10 jamie Jamie Bellaire
(4 row(s) affected)
这是我使用的测试用例:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
DROP TABLE [dbo].[Users]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GrobUsers]') AND type in (N'U'))
DROP TABLE [dbo].[GrobUsers]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FrobUsers]') AND type in (N'U'))
DROP TABLE [dbo].[FrobUsers]
GO
CREATE TABLE [dbo].[Users](
[Id] [int] NOT NULL,
[Username] [nchar](50) NULL,
[Fullname] [nchar](50) NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[GrobUsers](
[Id] [int] NOT NULL,
[Username] [nchar](50) NULL,
[Fullname] [nchar](50) NULL,
CONSTRAINT [PK_GrobUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[FrobUsers](
[Id] [int] NOT NULL,
[Username] [nchar](50) NULL,
[Fullname] [nchar](50) NULL,
CONSTRAINT [PK_FrobUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO Users Values (7,'iboyd','Ian Boyd' )
INSERT INTO Users Values (8,'nicholle','Nicholle Kuzniak' )
INSERT INTO Users Values (10,'jamie','Jamie Bellaire' )
INSERT INTO [GrobUsers] Values (7,'iboyd','Ian Alexander Boyd ' )
INSERT INTO [GrobUsers] Values (8,'nicholle','Nicholle Bachand' )
INSERT INTO [GrobUsers] Values (9,'chris','Chris Windibank' )
INSERT INTO [FrobUsers] Values (7,'iboyd','Ian' )
INSERT INTO [FrobUsers] Values (9,'nicholle','Chris W.' )
INSERT INTO [FrobUsers] Values (10,'jamie','James Bellaire' )
GO