我知道mysql查询这个吗?

oxosxuxt  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(150)

我的my know for 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

提前谢谢

jyztefdp

jyztefdp1#

一种方法是使用GROUPBY计算各个查询中各个表的总和,然后将结果连接到主查询中,如下所示。

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 |
+---------------+---------------+-------+

演示

rfbsl7qr

rfbsl7qr2#

现在还不清楚您是否只有一行输出,或者是否可以有多行输出,但这两种方式都有帮助:

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

相关问题