日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

sql查询两张表的并集union和union all

發(fā)布時間:2025/7/14 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 sql查询两张表的并集union和union all 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用 union all 和 union

1.新建兩張表:student、teacher
//學生表
create table student(
id int primary key,
name varchar(40)
);
//老師表
create table teacher(
id int primary key,
name varchar(40)
);

2.分別給兩張表加入一條記錄
insert into student(id,name) values(1,'student1');
insert into teacher(id,name) values(2,'teacher1');

3.查詢并集:
方式一(不去重復):
select * from student
union all
select * from teacher;

方式二(去掉重復):
select * from student
union
select * from teacher;

帶where子句的:
select * from student
where id = 1
union all
select * from teacher;

加字段區(qū)分記錄是數(shù)據(jù)哪個表的:
select a.*, '1' as belongf from student a
union all
select b.*, '0' as belongf from teacher b;

加order by子句:
select * from
(
select a.*, '1' as belongf from student a
union all
select b.*, '0' as belongf from teacher b
) t
order by belongf desc,id desc;

查并集的總記錄數(shù):
select count(1) as mycount from (
select a.*, '1' as belongf from student a
union all
select b.*, '0' as belongf from teacher b
) d;

?

轉(zhuǎn)載于:https://www.cnblogs.com/chentu279203653/p/9450143.html

總結(jié)

以上是生活随笔為你收集整理的sql查询两张表的并集union和union all的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。