交叉聯(lián)接是聯(lián)接查詢的第一個(gè)階段,它對(duì)兩個(gè)數(shù)據(jù)表進(jìn)行笛卡爾積。即第一張數(shù)據(jù)表每一行與第二張表的所有行進(jìn)行聯(lián)接,生成結(jié)果集的大小等于T1*T2。
-- 員工表
CREATE TABLE [dbo].[EmpInfo](
[empId] [int] IDENTITY(1,1) NOT NULL,
[empNo] [varchar](20) NULL,
[empName] [nvarchar](20) NULL,
CONSTRAINT [PK_EmpInfo] PRIMARY KEY CLUSTERED
(
[empId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF
, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
-- 獎(jiǎng)金表
CREATE TABLE [dbo].[SalaryInfo](
[id] [int] IDENTITY(1,1) NOT NULL,
[empId] [int] NULL,
[salary] [decimal](18, 2) NULL,
[seasons] [varchar](20) NULL,
CONSTRAINT [PK_SalaryInfo] 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]
-- 季度表
CREATE TABLE [dbo].[Seasons](
[name] [nchar](10) NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[EmpInfo] ON
INSERT [dbo].[EmpInfo] ([empId], [empNo], [empName]) VALUES (1, N'A001', N'王強(qiáng)')
INSERT [dbo].[EmpInfo] ([empId], [empNo], [empName]) VALUES (2, N'A002', N'李明')
INSERT [dbo].[EmpInfo] ([empId], [empNo], [empName]) VALUES (3, N'A003', N'張三')
INSERT [dbo].[SalaryInfo] ([id], [empId], [salary], [seasons])
VALUES (1, 1, CAST(3000.00 AS Decimal(18, 2)), N'第一季度')
INSERT [dbo].[SalaryInfo] ([id], [empId], [salary], [seasons])
VALUES (2, 3, CAST(5000.00 AS Decimal(18, 2)), N'第一季度')
INSERT [dbo].[SalaryInfo] ([id], [empId], [salary], [seasons])
VALUES (3, 1, CAST(3500.00 AS Decimal(18, 2)), N'第二季度')
INSERT [dbo].[SalaryInfo] ([id], [empId], [salary], [seasons])
VALUES (4, 3, CAST(3000.00 AS Decimal(18, 2)), N'第二季度 ')
INSERT [dbo].[SalaryInfo] ([id], [empId], [salary], [seasons])
VALUES (5, 2, CAST(4500.00 AS Decimal(18, 2)), N'第二季度')
INSERT [dbo].[Seasons] ([name]) VALUES (N'第一季度')
INSERT [dbo].[Seasons] ([name]) VALUES (N'第二季度')
INSERT [dbo].[Seasons] ([name]) VALUES (N'第三季度')
INSERT [dbo].[Seasons] ([name]) VALUES (N'第四季度')
-- 查詢每個(gè)人每個(gè)季度的獎(jiǎng)金情況 如果獎(jiǎng)金不存在則為0
SELECT a.empName,b.name seasons ,isnull(c.salary,0) salary
FROM EmpInfo a
CROSS JOIN Seasons b
LEFT OUTER JOIN SalaryInfo c ON a.empId=c.empId AND b.name=c.seasons
交叉聯(lián)接雖然支持使用WHERE子句篩選行,由于笛卡兒積占用的資源可能會(huì)很多,如果不是真正需要笛卡兒積的情況下,則應(yīng)當(dāng)避免地使用CROSS JOIN。建議使用INNER JOIN代替,效率會(huì)更高一些。如果需要為所有的可能性都返回?cái)?shù)據(jù)聯(lián)接查詢可能會(huì)非常實(shí)用。
到此這篇關(guān)于SQL Server中交叉聯(lián)接的用法介紹的文章就介紹到這了,更多相關(guān)SQL Server交叉聯(lián)接內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!