MySQL (Myisam) - Aggiorna il campo per il massimo dei due campi da diverse tabelle
-
16-09-2020 - |
Domanda
Ho due tabelle, t1
e t2
con due colonne ciascuna - id_user
e age
.
Come posso aggiornare t1.age
al massimo t1.age
e t2.age
per l'ID corrispondente e lasciare invariata t1.age
se non è presente alcun ID corrispondente in t2
.
Prima di aggiornare:
t1 +-------+---+ |id_user|age| +-------+---+ | 1| 5| +-------+---+ | 2| 10| +-------+---+ | 3| 10| +-------+---+ t2 +-------+---+ |id_user|age| +-------+---+ | 2| 12| +-------+---+ | 3| 8| +-------+---+ | 4| 20| +-------+---+.
dopo l'aggiornamento:
t1 +-------+---+ |id_user|age| +-------+---+ | 1| 5| +-------+---+ | 2| 12| +-------+---+ | 3| 10| +-------+---+.
Soluzione
Potrebbe voler provare:
UPDATE t1
JOIN t2 ON (t2.id_user = t1.id_user)
SET t1.age = t2.age
WHERE t2.age > t1.age;
.
Caso di prova:
CREATE TABLE t1 (id_user int, age int);
CREATE TABLE t2 (id_user int, age int);
INSERT INTO t1 VALUES (1, 5);
INSERT INTO t1 VALUES (2, 10);
INSERT INTO t1 VALUES (3, 10);
INSERT INTO t2 VALUES (2, 12);
INSERT INTO t2 VALUES (3, 8);
INSERT INTO t2 VALUES (4, 20);
.
Risultato:
SELECT * FROM t1;
+---------+------+
| id_user | age |
+---------+------+
| 1 | 5 |
| 2 | 12 |
| 3 | 10 |
+---------+------+
3 rows in set (0.00 sec)
. Altri suggerimenti
UPDATE t1
SET age = T2.age
FROM t1
INNER JOIN t2
ON t2.id_user = t1.id_user
WHERE t2.age > t1.age
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow