连接查询:
根据两个或多个表之间的关系,从这些表中查询数据。
目的:
实现多表查询。
分类:
内连接、外连接(左连接、右连接、全连接)、交叉连接。
使用T-SQL语言查询数据,它们属于数据查询语言(DQL:Data Query Language)。
假如有下面2张表,以它们举例说明:
产品信息表(ProductInfo):
标识列 Id int
产品编号 ProductNo varchar(50)
产品名称 ProductName nvarchar(100)
产品类型编号 ProductTypeId int
产品价格 ProductPrice decimal(18, 2)
产品数量 ProductCount int
产品备注 ProductRemark nvarchar(150)
产品类型表(ProductTypeInfo):
产品类型编号 ProductTypeId int
产品类型名称 ProductTypeName nvarchar(50)
use ProductManagementDB
go
-- 先创建好主表,指定主键
create table ProductTypeInfo
(
ProductTypeId int identity(1, 1) primary key not null,
ProductTypeName nvarchar(50) not null
)
go
-- 再创建好从表,指定外键
create table ProductInfo
(
Id int identity(10001, 1) primary key not null, -- 标识种子,自增量
ProductNo varchar(50) unique not null, -- 指定unique约束
ProductName nvarchar(100) not null,
ProductTypeId int not null foreign key references ProductTypeInfo(ProductTypeId), -- 指定ProductTypeInfo表中的ProductTypeId为外键
Prod
SQL Server数据库基础:使用T-SQL语言多表连接查询之内连接、外连接(左连接、右连接、全连接)、交叉连接。
于 2022-08-02 15:48:19 首次发布