可以说我有一张下表
id value1 value2 value1_plus_value2
0 1.0 2.2 null
1 2.1 3.5 null
2 5.2 2.9 null
3 1.5 1.4 null
和映射值表
value name
2.0 "almost three"
3.0 "about three"
3.5 "three and half"
5.5 "five point five"
6.0 "a lot more than five"
结果表应该看起来像
id value1 value2 value1_plus_value2
0 1.0 2.2 "about three"
1 2.1 3.5 "five point five"
2 5.2 2.9 "a lot more than five"
3 1.5 1.4 "about three"
这应该怎么做?使用一些外部脚本和循环来逐行执行是相当简单的,但也很可能有一些 sql 方法可以做到这一点;
通过以下,我可以为一行执行此操作:
select id, value1, value2, name, abs(value1+value2-value) as distance
from value, mapping
where id=1
group by distance
limit 1;
添加了 sqlfiddle 链接http://sqlfiddle.com/#!2/b1ac73/1
我想对所有行都这样做。并将找到的最接近的名称添加到值表中。
所以我想得到的表的元代码就像
select outerquery.value1, outerquery.value2, name as value1_plus_value2
from value as outerquery,
(
select id, value1, value2, name, abs(value1+value2-value) as distance
from value, mapping
where id = outerquery.id
group by distance
limit 1
) as subquery;
但显然我不能将数据从外部查询传递到子查询。但我确定我只是想错了。