MySQL用union把两张没有关联的表合并,并使用条件查询 您所在的位置:网站首页 sql两张表合并查询 MySQL用union把两张没有关联的表合并,并使用条件查询

MySQL用union把两张没有关联的表合并,并使用条件查询

2023-08-16 23:59| 来源: 网络整理| 查看: 265

MySQL用union把两张没有关联的表合并,并使用条件查询

1.当两张表属性完全相同时,可以直接合并(union会删除重复数据,union all会返回所有结果集) (1)将两个表合并

select * from 表1 union select * from 表2 select * from 表1 union all select * from 表2

(2)将两个表合并,并使用条件查询

select * from ( select * from 表1 union select * from 表2) as 新表名 where 条件1 and 条件2

2、当两个表的属性不同时,要分别查询每个属性,给不同属性名取一个别名,例如收入和支出表:(表中的id和remark是相同属性名,其他的属性名都不同)

在这里插入图片描述

在这里插入图片描述

select * from( (select id, inform as form, income as come, incomer as comer, intype as type, insource as source, remark from incometable) union all (select id, outform as form, outcome as come, outcomer as comer, outtype as type, outsource as source, remark from outcometable) ) as report

还能加查询条件

where 条件1 and 条件2

在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有