如何加入这2个mysql查询?

时间:2013-01-07 15:32:10

标签: mysql join

我希望能够加入2种复杂的查询,但不太确定要执行此操作的语法。

查询1:

select month(Date_1) as Date_1, 
       sum(number_1) as number_1 
  from table_1 
  where Date_1 between '2012-01-01' and '2013-01-01' 
  group by month(Date_1);

给出了这个结果:

enter image description here

查询2:

select count(distinct number_2) as number_2, 
       month(Date_2) as Date_2 
  from table_2 
  where Date_2 between '2012-01-01' and '2013-01-01' 
  group by month(Date_2) 
  order by month(Date_2) desc;

给出了这个结果:

enter image description here

我想加入这两个查询,以便在Date_1和Date_2列相等时,number_1与number_2匹配。每月一排。

有谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

select T1.Date_1, T1.number_1, T2.number_2 from 

(select month(Date_1) as Date_1, 
       sum(number_1) as number_1 
  from table_1 
  where Date_1 between '2012-01-01' and '2013-01-01' 
  group by month(Date_1))T1

inner join

(select count(distinct number_2) as number_2, 
       month(Date_2) as Date_2 
  from table_2 
  where Date_2 between '2012-01-01' and '2013-01-01' 
  group by month(Date_2) 
  order by month(Date_2) desc)T2

on T1.Date_1 = T2.Date_2;

基本上,加入月份的两个临时表(由于查询而形成)。