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