2016-08-22 56 views
-2

我需要一些帮助来解决我的查询问题。我想加入两个SELECT语句的输出:我需要在mysql中加入两个表

select extract(year from createdDate) as year, 
     count(extract(year from createdDate)) as count 
from table 
where to_user_id= 322 
group by extract(year from createdDate); 

,其输出

Year Count 
2014 18 
2015 117 
2016 9 

和第二查询

select count(extract(year from createdDate)) as count 
from table 
where userId=322 
group by extract(year from createdDate); 

,其输出

Count 
    18 
    110 
    11 

我想将这两个表添加到一个表中。 我想这类型的输出,

Year Count Count 
2014 18  18 
2015 117 110 
2016 9  11 

请注意,我用的查询1 to_user_iduserId查询2.

我试图解决这项事情,但我得到了在输出重复值。 任何人都知道解决方案?

+0

为什么两个查询对同一事物得到不同的计数? – Barmar

+0

您可以发布构建查询的表格结构。 –

+0

他们是从不同的表格查询吗?两个查询中都有相同的表名。 – Barmar

回答

3

将它们写成子查询并将它们结合在一起。

SELECT a.year, a.count AS t_user_count, b.count AS user_count 
FROM (select YEAR(create_date) AS year, COUNT(*) AS count 
     FROM table 
     WHERE to_user_id = 322 
     GROUP BY year) AS a 
JOIN (SELECT YEAR(create_date) AS year, COUNT(*) AS count 
     FROM table 
     WHERE user_id = 322 
     GROUP BY year) AS b 
ON a.year = b.year 
+0

工程像魅力。谢谢@barmar – Darshan