【发布时间】:2014-11-06 09:36:23
【问题描述】:
我有两张桌子。
我需要将这两个表的每一行组合成 table3 中的一行。我设法得到了 table1 SUM 的金额,但不是 table2。
例如。
表用户
+---------+-----------+
| user_id | user_name |
+---------+-----------+
| 001 | JOHN |
| 002 | ADAM |
+---------+-----------+
table1
+-----------+----------------+-------------------+---------------------+
| table1_id | table1_user_id | table1_amount | table1_date |
+-----------+----------------+-------------------+---------------------+
| 6 | 001 | 100 | 01/11/2014 10:55 |
| 7 | 002 | 100 | 01/11/2014 10:55 |
| 8 | 001 | 50 | 25/10/2014 10:55 |
| 9 | 001 | 100 | 23/10/2014 11:00 |
| 10 | 002 | 0 | 21/10/2014 11:00 |
+-----------+----------------+-------------------+---------------------+
table2
+-----------+----------------+----------------+--------------------+
| table2_id | table2_user_id | table2_amount | table2_date |
+-----------+----------------+----------------+--------------------+
| 1 | 001 | 100 | 15/11/2014 10:55 |
| 2 | 001 | 100 | 15/10/2014 10:55 |
| 3 | 002 | 100 | 11/10/2014 10:55 |
| 4 | 001 | 50 | 11/10/2014 10:55 |
+-----------+----------------+----------------+--------------------+
预期结果:
表3
+-----+---------+---------------+---------------+----------+---------+
| id | user_id | table1_amount | table2_amount | Year | Month |
+-----+---------+---------------+---------------+----------+---------+
| 1 | 001 | 100 | 100 | 2014 | 11 |
| 2 | 002 | 100 | 0 | 2014 | 11 |
| 3 | 001 | 150 | 150 | 2014 | 10 |
| 4 | 002 | 0 | 100 | 2014 | 10 |
+-----+---------+---------------+---------------+----------+---------+
我的尝试,但它没有显示预期的结果。每行table2_amount的数量为NULL:
SQL=" INSERT INTO table3
SELECT user_id,SUM(table1_amount),t2.amount2,
YEAR(table1_date),MONTH(table1_date) FROM table1 a
LEFT JOIN
(SELECT c.table2_user_id,SUM(c.table2_amount) as amount2,c.table2_date
FROM table2 c
GROUP BY DATE_FORMAT(c.table2_date,'%Y-%m'),c.table2_user_id ASC
) t2
on t2.table2_user_id = a.table1_user_id AND t2.table2_date = a.table1_date
GROUP BY DATE_FORMAT(a.table1_date,'%Y-%m'),table1_user_id ASC ";
"
【问题讨论】:
-
“它不起作用”是什么意思?你有错误吗?你得到不好的结果吗?请详细说明
-
很抱歉它没有显示预期的结果。 @不知道名字
-
你为什么使用左连接?表是如何连接的?
-
table1和table2具有相同的属性:user_id;table1.table1_user_id=table2.table2_user_id=user.@987654336 -
好吧,检查内部选择。如果没问题,则联接不会返回任何对,并且 LEFT 字会使其仅从 table1 中获取行。我认为比较日期不好,除非你绝对确定它们会相同
标签: mysql