我知道MysQL查询吗?
它可以在1个sql语句或2个sql语句中吗?
Table1
id main rate
1 10 3 | 10 * 3 = 30
total = 30
table2
id table1_id value newnum
1 1 20 3 | 20 * 3 = 60
2 1 30 2 | 30 * 2 = 60
3 1 22 3 | 22 * 3 = 66
4 1 0 0
total = 186
Result
table1_result table2_result final
30 186 216
提前致谢
答案 0 :(得分:0)
不清楚你是否只有一行,或者你可以有多行输出,但这应该有助于:
select id, main*rate t1.table1_result, t2.table2_result
from table_1 t1
inner join (
select table1_id, sum(value * newnum) table2_result
from table_2
group by table1_id
) t2 on t1.id = t2.t1id
-- optional
where t1.id = 1
答案 1 :(得分:0)
一种方法是使用group by计算各个查询中各个表的总和,然后在主查询中加入结果,如下所示。
SELECT table1_result,
table2_result,
table1_result + table2_result AS FINAL
FROM
(SELECT id,
sum(main*rate) AS table1_result
FROM table1 t1
GROUP BY id) AS t1
JOIN
(SELECT table1_id,
sum(value*newnum) AS table2_result
FROM table2 t2
GROUP BY table1_id ) AS t2 ON t1.id = t2.table1_id
<强>结果:强>
+---------------+---------------+-------+
| table1_result | table2_result | final |
+---------------+---------------+-------+
| 30 | 186 | 216 |
+---------------+---------------+-------+
<强> DEMO 强>