Bonsoir a tous,

Y a un truc que ne fait pas bien, mais je ne comprend pas quoi.

Contexte très classique, 3 table:
  • une table commande
  • une table item (article)
  • entre les 2 table précedente une table item_list (liste d'articles) qui pointe sur les deux tables précédentes.


Le script suivant crée les tables automatiquement, et initialise la table article sans aucune erreur :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 
drop table if exists test_item;
drop table if exists test_commande;
drop table if exists test_item_list;
 
create table test_item
(
   id_test_item              int not null,
   lib_item             varchar(255) not null,
   primary key (id_test_item)
)ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 
create table test_commande
(
   id_test_commande          int not null auto_increment,
   description_commande varchar(256),
   primary key (id_test_commande)
)ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 
create table test_item_list
(
   id_test_item         int not null,
   id_test_commande          int not null,
   quantity             int not null,
   primary key (id_test_item, id_test_commande)
)ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 
/* ALTER TABLE test_item_list DROP FOREIGN KEY fk_item_list; */
 
alter table test_item_list add constraint fk_item_list foreign key (id_test_item)
      references test_item (id_test_item) on delete restrict on update restrict;
 
/* ALTER TABLE test_item_list DROP FOREIGN KEY fk_item_list2; */
 
alter table test_item_list add constraint fk_item_list2 foreign key (id_test_commande)
      references test_commande (id_test_commande) on delete restrict on update restrict;
 
INSERT INTO `test`.`test_item` (`id_test_item`, `lib_item`) VALUES ('0', 'article 0'), ('1', 'article 1');
Maintenant :
J'ajoute un commande, je récupère l'id (auto-increment) que j'utilise pour ajouter 2 articles (dans test_list_item) via cette requete :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
 
START TRANSACTION;
INSERT INTO `test_commande` (`description_commande`) VALUES ('ma commande');
SELECT LAST_INSERT_ID() INTO @last_id from `test_commande`;
INSERT INTO `test_item_list` ( `id_test_item` ,  `quantity` ,  `id_test_commande` ) VALUES ('0' , '0' , @last_id ),('1' , '0' , @last_id );
COMMIT;
SELECT @last_id;
La premiere fois cette requete fonctionne, j'ai bien ma commande et les 2 articles.
Si je relance la requete (sans effacer les éléments précédents), j'ai ce message :

SELECT LAST_INSERT_ID( ) INTO @last_id FROM `test_commande` ;

MySQL a répondu:
#1172 - Result consisted of more than one row
je suis triste.. ze comprend pas..

Quelqu'un peut m'aider ?