找到最接近的值 - MySQL

时间:2016-05-25 15:00:16

标签: mysql

如何找到多个值的最接近值?

例如: 我有这张桌子

A 1

B 2

C 3

D 7

E 11

F 12

所以 -

for A i want to get B, 
for B - A and C,
for C - B,
for D - E,
for E - F,
for F - E,

由于

2 个答案:

答案 0 :(得分:5)

试试这个:

SELECT t1.col1, t2.col1
FROM mytable AS t1
INNER JOIN mytable AS t2 
  ON t1.col1 <> t2.col1
LEFT JOIN mytable AS t3 
  ON t3.col1 <> t2.col1 AND t3.col1 <> t1.col1 AND 
     ABS(t3.col2 - t1.col2) < ABS(t2.col2 - t1.col2)
WHERE t3.col1 IS NULL  
ORDER BY t1.col1

Demo here

答案 1 :(得分:1)

你可以使用像这样的小翻译表

CREATE TABLE `translate` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `from` char(1) DEFAULT NULL,
  `to` char(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `from` (`from`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

INSERT INTO `translate` (`id`, `from`, `to`)
VALUES
    (1, 'A', 'B'),
    (2, 'B', 'A'),
    (3, 'B', 'C'),
    (4, 'C', 'B'),
    (5, 'D', 'E'),
    (6, 'E', 'F'),
    (7, 'F', 'E');

<强>示例

    MariaDB []> SELECT * FROM yourTable;
+----+------+------+
| id | c    | val  |
+----+------+------+
|  1 | A    |    1 |
|  2 | B    |    2 |
|  3 | C    |    3 |
|  4 | D    |    7 |
|  5 | E    |   11 |
|  6 | F    |   12 |
+----+------+------+
6 rows in set (0.00 sec)

MariaDB []>
MariaDB []> SELECT y.*
    -> FROM yourTable y
    -> LEFT JOIN translate t ON t.to = y.c
    -> WHERE t.from = 'C';
+----+------+------+
| id | c    | val  |
+----+------+------+
|  2 | B    |    2 |
+----+------+------+
1 row in set (0.00 sec)

MariaDB []> SELECT y.*
    -> FROM yourTable y
    -> LEFT JOIN translate t ON t.to = y.c
    -> WHERE t.from = 'B';
+----+------+------+
| id | c    | val  |
+----+------+------+
|  1 | A    |    1 |
|  3 | C    |    3 |
+----+------+------+
2 rows in set (0.00 sec)

MariaDB []>