如何将两个查询的结果放在同一个表中

时间:2015-01-14 18:12:49

标签: mysql select

在MySQL中,我有两个包含许多事务的表。我正在使用两个SELECT查询,两个查找结果,如下所示,但我找不到一种方法将它们放在一起,如在帖子的末尾。以下是查询的详细信息及其结果:

查询1:

SELECT SUM( o.paid ) AS Income, DATE( FROM_UNIXTIME( o.time ) ) AS DATE
FROM  `orders_successful` AS o
WHERE DATE( FROM_UNIXTIME( o.time ) ) < CURDATE( ) 
AND o.type <>8
GROUP BY DATE( FROM_UNIXTIME( o.time ) ) 
ORDER BY o.time DESC 
LIMIT 5

查询2:

SELECT SUM( t.amount ) AS Commissions, DATE( t.datetime ) AS DATE
FROM  `tb_user_txns` AS t
WHERE DATE( t.datetime ) < CURDATE( ) 
GROUP BY DATE( t.datetime ) 
ORDER BY t.datetime DESC 
LIMIT 5

查询1的结果:

+--------+------------+
| Income |    Date    |
+--------+------------+
| 4,667  | 13-01-2015 |
| 4,118  | 12-01-2015 |
| 3,427  | 11-01-2015 |
| 3,484  | 10-01-2015 |
| 3,711  | 09-01-2015 |
+--------+------------+

查询2的结果:

+-------------+------------+
| Commissions |    Date    |
+-------------+------------+
|         350 | 13-01-2015 |
|         300 | 12-01-2015 |
|         225 | 11-01-2015 |
|         211 | 10-01-2015 |
|         262 | 09-01-2015 |
+-------------+------------+

好的,我想做的是这样的输出:

+--------+-------------+------------+
| Income | Commissions |    Date    |
+--------+-------------+------------+
| 4,667  |         350 | 13-01-2015 |
| 4,118  |         300 | 12-01-2015 |
| 3,427  |         225 | 11-01-2015 |
| 3,484  |         211 | 10-01-2015 |
| 3,711  |         262 | 09-01-2015 |
+--------+-------------+------------+

1 个答案:

答案 0 :(得分:1)

您可以将查询作为子查询,然后加入

如果日期不存在于另一个查询中,您可以将联接更改为left join以获取一个查询的所有结果。

select t1.Income,
       t2.Comissions,
       t1.Date
from ( first query here ) t1
join ( second query here ) t2
on t1.date = t2.date