Bonjour,

j'ai 2 tables (customer et country) et la table customer contient un champ country_key à mettre à jour si le customer a changé de country.

Voici la structure des 2 tables :
Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
  `customer_login_id` int NOT NULL AUTO_INCREMENT,
  `country_key` smallint DEFAULT NULL,
  `organization` varchar(50) COLLATE utf8_bin DEFAULT NULL,
  UNIQUE KEY `customer_login_id_UNIQUE` (`customer_login_id`),
  KEY `FK_COUNTRY3` (`country_key`),
  CONSTRAINT `FK_COUNTRY3` FOREIGN KEY (`country_key`) REFERENCES `country` (`country_key`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=27001 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
  `country_key` smallint NOT NULL AUTO_INCREMENT,
  `country` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
  `region` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT '',
  PRIMARY KEY (`country_key`),
  UNIQUE KEY `uk_country` (`country`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

et les 3 requêtes essayées :
Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
UPDATE    customer
SET              country_key = country.country.key
FROM         country, customer
WHERE     country.country = 'valeur_de_country' and customer_SESA=xxx

Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
update customer.country_key=country.country_key
from customer, country
where  country.country = 'valeur_de_country' and customer_SESA=xxx

Code sql : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
update customer cu
set  cu.country_key = (SELECT FROM country co
where co.country = 'valeur_de_country') where cu.customer_SESA=xxx

Je me suis inspiré ce cette ancienne discussion : https://www.developpez.net/forums/d2869/bases-donnees/langage-sql/requete-update-partir-d-table mais ce n'était pas du MySQL et dans les 3 cas, ça me dit "erreur SQL". Pouvez-vous me proposer un truc qui fonctionne ?

Par exemple, avant, le customer était dans le country "Argentina" et le country_key était 1 mais il vient de passer dans le country "Brazil" et du coup le customer_key doit passer à 2.