Table_1
+------+-------------+
| id | value |
+------+-------------+
| 1 | 1.58 |
| 2 | 8.88 |
+------+-------------+
Table_2
+------+-------------+
| id | value |
+------+-------------+
| 1 | 2.15 |
| 2 | 7.50 |
+------+-------------+
Table_3
+------+-------------+
| id | value |
+------+-------------+
| 1 | 9.58 |
| 2 | 2.88 |
+------+-------------+
Result
+------+-------------------+
| id | value |
+------+-------------------+
| 1 | 1.58 (min value) |
| 2 | 2.88 (min value) |
+------+-------------------+
你好,我对mysql不是很熟悉。
我想从不同的表中计算关于 ID 的最小值,并将其存储在结果表中。我怎样才能做到这一点?
最佳答案
一种选择是在子查询中使用union all
。然后对结果使用 min
聚合:
select id, min(value) val
from (
select id, value
from table_1
union all
select id, value
from table_2
union all
select id, value
from table_3
) t
group by id
或者您可以将表连接
并使用least
(假设所有表都具有相同数量的id
字段并且只有1个每个 id
的行)。
select t1.id, least(t1.value, t2.value, t3.value) val
from t1
join t2 on t1.id = t2.id
join t3 on t1.id = t3.id
编辑:关于您的评论,只需添加CREATE TABLE
。
create table newtable
select ...
关于mysql - 从不同的表中获取最小值并保存在结果表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35931858/