如果我们需要将两个select语句的结果作为一个整体显示出来,我们就需要用到union或者union all关键字。union(或称为联合)的作用是将多个结果合并在一起显示出来。
注意:两个列表中的字段要一样才可以合并(顺序也要一样)
满足条件:
1、两个select查询的列的数量必须相同;
2、每个列的数据类型需要相似;
第一条select:
SELECT
DATE_FORMAT(add_time, '%Y-%m-%d') as 'add_time',
COUNT(add_time) as 'reach_intention'
FROM
table1
where
## where 条件可以根据自己实际情况来定
DATE_FORMAT(add_time, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 1 month), '%Y-%m-%d')
group by
DATE_FORMAT(add_time, '%Y-%m-%d')
select
DATE_FORMAT(add_date, '%Y-%m-%d') as 'add_time' ,
COUNT(add_date) as 'post_release'
from
table2
where
## where 条件可以根据自己实际情况来定
DATE_FORMAT(add_date, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 1 month), '%Y-%m-%d')
group by
DATE_FORMAT(add_date, '%Y-%m-%d')
SELECT
DATE_FORMAT(add_time, '%Y-%m-%d') as 'add_time', COUNT(add_time) as 'reach_intention' , '' as 'post_release'
FROM
table1
where
DATE_FORMAT(add_time, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 30 day), '%Y-%m-%d')
group by
DATE_FORMAT(add_time, '%Y-%m-%d')
UNION ALL
select
DATE_FORMAT(add_date, '%Y-%m-%d') as 'add_time' , '' as 'reach_intention' , COUNT(add_date) as 'post_release'
from
table2
where
DATE_FORMAT(add_date, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 30 day), '%Y-%m-%d')
group by
DATE_FORMAT(add_date, '%Y-%m-%d')
## 括号里面放 用 union all 连接的select
select * from () test
## 这里要给表起个别名 不然会报 Every derived table must have its own alias 每个派生表都必须有自己的别名
select
*
from
(
SELECT
DATE_FORMAT(add_time, '%Y-%m-%d') as 'add_time', COUNT(add_time) as 'reach_intention' , '' as 'post_release'
FROM
table1
where
DATE_FORMAT(add_time, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 30 day), '%Y-%m-%d')
group by
DATE_FORMAT(add_time, '%Y-%m-%d')
UNION ALL
select
DATE_FORMAT(add_date, '%Y-%m-%d') as 'add_time' , '' as 'reach_intention' , COUNT(add_date) as 'post_release'
from
table2
where
DATE_FORMAT(add_date, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 30 day), '%Y-%m-%d')
group by
DATE_FORMAT(add_date, '%Y-%m-%d')
) test
select
add_time,
sum(reach_intention) as 'reach_intention' ,
sum(post_release) as 'post_release'
from
(
SELECT
DATE_FORMAT(add_time, '%Y-%m-%d') as 'add_time', COUNT(add_time) as 'reach_intention' , '' as 'post_release'
FROM
table1
where
DATE_FORMAT(add_time, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 30 day), '%Y-%m-%d')
group by
DATE_FORMAT(add_time, '%Y-%m-%d')
UNION ALL
select
DATE_FORMAT(add_date, '%Y-%m-%d') as 'add_time' , '' as 'reach_intention' , COUNT(add_date) as 'post_release'
from
table2
where
DATE_FORMAT(add_date, '%Y-%m-%d') > DATE_FORMAT(date_sub(now(), interval 30 day), '%Y-%m-%d')
group by
DATE_FORMAT(add_date, '%Y-%m-%d') ) test
group by
test.add_time
order by
test.add_time desc