多表查询是SQL数据库里的高级查询语句。
创建3个数据库,做演示。
create database NetBarDB --创建数据库create database 数据库名
go --批处理(数据库无法自动运行下一句代码,需要加go来继续代码的运行)
use NetBarDB --打开数据库
go
if exists(select * from sys.objects where name='PCInfo')
begin
drop table PCInfo
end
create table Stufo
(
StuId int primary key identity,
StuName char(10) unique not null, --姓名,约束:unique【唯一的】和主键一样有唯一标识,表示内容不能有重复数据,not null不为空;
)
create table PCInfo
(
PCId int primary key identity,
PCScore int not null, --成绩
PCScore2 int --成绩
)
create table cardInfo
(
id int primary key identity,
age int not null , --年龄
sex char(2), --性别
)
insert into Stufo values('张三'),('李四'),('王五')
insert into PCInfo values(5,40),(10,70),(60,100)
insert into cardInfo values(18,'男'),(19,'女'),(20,'男')
select * from Stufo
select * from PCInfo
select * from cardInfo
多表高级查询语句。
--联合查询: select * from 表1,表2,表n where 条件1 and 条件2 and 条件n
select * from Stufo,PCInfo,cardInfo where StuId=PCId and PCId=id --两个表只需要一个条件就可以,and后面的条件可以不用
--联接查询:join 注意:返回的数据,与另一个表没有关联数据时,都是NULL
--内连接:inner join 返回:两个表的公共部份数据(交集),不匹配的数据直接不显示。
select * from PCInfo inner join cardInfo on PCInfo.PCId=cardInfo.age
select StuName as 姓名,
cardInfo.age as 年龄,
cardInfo.sex as 性别,
PCInfo.PCScore as 成绩
from PCInfo inner join Stufo on PCInfo.PCId=Stufo.StuId inner join cardInfo on PCInfo.PCId = cardInfo.id
--左连接:left join 返回:左表所有数据,及与右表公共部份数据
select * from PCInfo left join cardInfo on PCInfo.PCScore=cardInfo.id
--右连接:right join 返回:右表所有数据,及与左表公共部份数据
select * from PCInfo right join cardInfo on PCInfo.PCScore=cardInfo.id
--外连接:full join 返回:两个表的所有数据
select * from PCInfo full join cardInfo on PCInfo.PCId=cardInfo.age
--扩展
select top 1 * from PCInfo inner join cardInfo on PCInfo.PCId=cardInfo.id order by PCInfo.PCScore desc --根据成绩排序,查成绩第一名
select top 2 StuName 姓名,(PCScore+PCScore2)/2 as 成绩
from PCInfo,Stufo where PCInfo.PCId=Stufo.StuId order by ((PCScore+PCScore2)/2) desc --平均分最高的两个人
--并集union:去掉重复数据,把两个表数据叠加在一起
select COUNT(*) from PCInfo where PCScore2=100
union
select COUNT(*) from cardInfo where sex='女'
--并集union all:不会去掉重复
select COUNT(*) from PCInfo where PCScore2=100
union all
select COUNT(*) from cardInfo where sex='女'
--交集intersect:两个表相同的数据显示出来
select PCInfo.PCScore from PCInfo
intersect
select cardInfo.id from cardInfo
--差集except:自动删除两表重复行。并且只显示表1,不显示表2,表1在表2有的数据也不显示
select PCScore from PCInfo
except
select cardInfo.id from cardInfo
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/bigdata/289767.html