MySQL在最接近的匹配值上加入两个表

时间:2018-03-02 06:25:00

标签: mysql join

我有以下情况:

tableA
+-------+-------+
| id    | Value |
+-------+-------+
| 1     | 1000  |
| 2     | 20    |
| 3     | 62    |
| 4     | 0     |
+-------+-------+

tableB
+-------+--------+
| Value | Lookup |
+-------+--------+
|    10 | a      |
|    20 | b      |
|    30 | b      |
|    40 | g      |
|    50 | h      |
|    60 | f      |
|    70 | a      |
|    80 | a      |
|    90 | v      |
|   100 | b      |
+-------+--------+

我需要返回表B中与表A中的值字段最匹配的查找。例如。

+-------+-------+--------+
| id    | Value | Lookup |
+-------+-------+--------+
| 1     | 1000  | b      |
| 2     | 20    | b      |
| 3     | 62    | f      |
| 4     | 0     | a      |
+-------+-------+--------+

我该怎么做呢?

2 个答案:

答案 0 :(得分:4)

这是一个使用连接的选项:

SELECT
    a.Id, a.Value, b.Lookup
FROM tableA a
CROSS JOIN tableB b
INNER JOIN
(
    SELECT a.Id, MIN(ABS(a.Value - b.Value)) AS min_abs_value
    FROM tableA a
    CROSS JOIN tableB b
    GROUP BY a.Id
) t
    ON a.Id = t.Id AND
       ABS(a.Value - b.Value) = t.min_abs_value;

enter image description here

Demo

当此查询 加入子查询时,子查询不相关。

答案 1 :(得分:2)

一种方法是使用相关子查询:

SELECT a.Id, a.Value, 
       (SELECT b.Lookup
       FROM TableB AS b
       ORDER BY ABS(a.Value - b.Value) LIMIT 1)
FROM TableA AS a

Demo here