最新SQL合并两个表的数据并按条件筛选两个表的结果集

最新SQL合并两个表的数据并按条件筛选两个表的结果集

我们都知道合并两个表使用union all对两个表进行连接。
例如:

查询表Student1和表Student2的合并后的信息

select name,age,sex,password from Student1
 union all select name,age,sex,password from Student2

那么如何对合并后的两个表进行条件筛选呢?
很简单。操作如下

查询表Student1和表Student2的合并后,名字叫zhangsan的所有学生信息

 select * from  (select name,age,sex,password from Student1
     union all select name,age,sex,password from Student2) 
     	where name='zhangsan'

你学到了吗?
我这边已经在Oracle数据库上面测试过了完美运行。
MYSQL数据库合并语句示例:

select t.* from (SELECT id,name from tb_hero  
UNION ALL select id,name  FROM tb_hero2)t 
where id = 1

区别在于在MYSQL数据库上,对合并后的结果集添加了一个别名t。在MYSQL数据库上完美运行。希望大家能多多支持,我会把我觉得很实用的东西分享给大家。

猜你喜欢

转载自blog.csdn.net/weixin_43440301/article/details/84067074
今日推荐