我有这张桌子:
CREATE TABLE table1 (
id INT NOT NULL PRIMARY KEY,
value1 INT NOT NULL,
value2 INT NOT NULL
);
CREATE TABLE table2 (
id INT NOT NULL PRIMARY KEY,
table1_id INT NOT NULL,
valuex INT NOT NULL
);
INSERT INTO table1 (id, value1, value2)
VALUES
(1, 10, 15),
(2, 5 , 3);
INSERT INTO table2 (id, table1_id, valuex)
VALUES
(1, 1, 15),
(2, 1, 25),
(3, 2, 14),
(4, 2, 10);
有了这个:
SELECT COUNT(`table1`.`id`) AS `orders`,
SUM(`value1`) as `sum_value1`, SUM(`value2`) as `sum_value2`,
SUM(`valuex`) as `sum_valuex`
FROM `table1`
INNER JOIN `table2`
ON `table1`.`id` = `table2`.`table1_id`
我得到了输出:
+----------------------------------------------+
+ orders | sum_value1 | sum_value2 |sum_valuex +
+----------------------------------------------+
+ 4 | 30 | 36 | 64 +
+----------------------------------------------+
但我在table1中只有两个订单。我知道由于连接而重复,但是如何通过添加sum_valuex来解决这个问题呢?
我想要的结果是:
+----------------------------------------------+
+ orders | sum_value1 | sum_value2 |sum_valuex +
+----------------------------------------------+
+ 2 | 15 | 18 | 64 +
+----------------------------------------------+
编辑:我不能在select
中使用select答案 0 :(得分:2)
这是加入工作的方式。如果您不希望在聚合之前将行相乘,则在执行join
之前聚合。
SELECT t2.orders, t1.value1, t1.value2, t2.sum_valuex
FROM `table1` INNER JOIN
(SELECT table1_id, SUM(valuex) as sum_valuex, COUNT(*) as orders
FROM table2
GROUP BY table1_id
) t2
ON t1.id = t2.table1_id
答案 1 :(得分:0)
哪个表有订单?现在,你的count(table1.id)正在计算表2中的记录。(表2中这是该列的位置)如果Table1是包含其中订单的表,那么你应该计算表1中的记录< / p>
SELECT COUNT(distinct a.id) orders,
SUM(value1) as sum_value1`, SUM(value2) as sum_value2,
SUM(valuex) as sum_valuex
FROM table1 a
JOIN table2 b
ON b.table1_id = a.id
答案 2 :(得分:0)
你可以得到这样的欲望结果:
将count(订单)作为订单,SUM(t1.value1)作为value1,SUM(t1.value2)作为value2,SUM(t2.sum_valuex)作为sumvaluex FROM table1 t1 INNER JOIN (SELECT table1_id,SUM(valuex)为sum_valuex,COUNT(*)为订单 从table2 GROUP BY table1_id )t2 ON t1.id = t2.table1_id
请不要忘记标记我的答案:)