我有一个像下面这样的 mysql 表
id id_dosen id_dosen2 tetangga1 tetangga2
1 1 2 null null
2 2 3 null null
3 1 3 null null
4 4 5 null null
5 4 6 null null
6 6 null null null
我需要将第 1 行的 id_dosen 和 id_dosen2 与所有其他行上的比较,并从第 2 行开始做同样的事情,依此类推,举个例子,我需要知道第 1 行是否与其他行具有相同的值,如果有然后是对 tetangga1 和 tetangga 2 的触发更新,其中 tetangga1 和 tetangga2 中的值将是与当前行具有相同值的行的 ID,因此表格将像这样
id id_dosen id_dosen2 tetangga1 tetangga2
1 1 2 2 3
2 2 3 1 3
3 1 3 1 2
4 4 5 5 null
5 4 6 4 6
6 6 null 5 null
解释:第 1 行的 tetangga1 列中将包含第 2 行的 ID,因为第 1 行的 id_dosen2 与第 2 行的 id_dosen 具有相同的值。 第 1 行将在其 tetangga2 列中包含第 3 行的 id,因为第 1 行的 id_dosen 与第 3 行的 id_dosen 具有相同的值
谁能帮帮我?
最佳答案
这在 MySQL 中绝对不是一个容易解决的问题,但它是可行的。此查询 ( SQLFiddle) 适用于您的样本数据:
UPDATE table1, (SELECT id, tetangga1, IF(tetangga2 = tetangga1, NULL, tetangga2) AS tetangga2
FROM (SELECT t1.id AS id, MIN(t2.id) AS tetangga1, MAX(t2.id) AS tetangga2
FROM table1 t1
JOIN table1 t2
ON (t2.id_dosen = t1.id_dosen OR t2.id_dosen = t1.id_dosen2 OR
t2.id_dosen2 = t1.id_dosen OR t2.id_dosen2 = t1.id_dosen2) AND
t2.id != t1.id
GROUP BY t1.id) t3) t4
SET table1.tetangga1 = t4.tetangga1, table1.tetangga2 = t4.tetangga2
WHERE table1.id = t4.id
关于mysql - 比较表中的两个值并使用触发器更新另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50322469/