如何使用来自多个表的信息更新表[关闭]
Posted
技术标签:
【中文标题】如何使用来自多个表的信息更新表[关闭]【英文标题】:How to update table using information from multiple tables [closed] 【发布时间】:2020-05-02 10:30:12 【问题描述】:我的数据库中有 3 个表。
表1:
+---------+----------+---------+-----+
| name | order_no | comment | sum |
+---------+----------+---------+-----+
| John | 1 | | |
| Dimitri | 3 | | |
| Peter | 6 | | |
+---------+----------+---------+-----+
表2:
+-------------+------------+-------+
| fk_order_no | fk_film_no | count |
+-------------+------------+-------+
| 1 | 10 | 20 |
| 1 | 15 | 15 |
| 3 | 15 | 30 |
| 3 | 16 | 16 |
| 6 | 69 | 37 |
+-------------+------------+-------+
表3:
+----------------------+---------+-------+
| name | film_no | price |
+----------------------+---------+-------+
| Pacific Rim | 10 | 16.5 |
| Pacific Rim Uprising | 15 | 13.3 |
| Pacifier | 16 | 11.01 |
| Package | 69 | 0.34 |
| Pagemaster | 22 | 0.14 |
| Painted Veil | 66 | 0.17 |
+----------------------+---------+-------+
我想更新 table1 的 sum 列。总和是这样计算的
sum (order_no = 1) = 20 (count from table2) * 16.5 (price from table3) + 15 (count from table2) * 13.3 (price from table 3)
sum(order_no = 3 )= 30 * 13.3 + 16 * 11.01
sum(order_no=6) = 37 * 0.34
table1 应该如下所示:
+---------+----------+---------+--------+
| name | order_no | comment | sum |
+---------+----------+---------+--------+
| John | 1 | | 529.5 |
| Dimitri | 3 | | 575.16 |
| Peter | 6 | | 12.58 |
+---------+----------+---------+--------+
【问题讨论】:
尝试用SQL写这个伪代码 你的问题是什么? @NicoHaase。如何从 table1 更新列总和 到目前为止你尝试了什么? 我尝试了 Gordon 的答案,但出现错误:# 1054 - 'on Clause' 中的未知列 't2.fk_order_no'。 @NicoHaase 【参考方案1】:嗯。 . .计算的数据来自join
和聚合:
select t2.fk_order_no, sum(t2.count * t3.price)
from table2 t2 join
table3 t3
on t2.fk_film_no = t3.film_no
group by t2.fk_order_no;
然后您可以使用 join
将其合并到 update
中:
update table1 t1 join
(select t2.fk_order_no, sum(t2.count * t3.price) as total_price
from table2 t2 join
table3 t3
on t2.fk_film_no = t3.film_no
group by t2.fk_order_no
) t23
on t1.order_no = t23.fk_order_no
set t1.sum = t23.total_price;
【讨论】:
谢谢。第一部分完美运行。但是,当我尝试编译第二个查询时,出现错误:#1054 - Unknown column 't2.fk_order_no' in 'on Clause'以上是关于如何使用来自多个表的信息更新表[关闭]的主要内容,如果未能解决你的问题,请参考以下文章