Domanda

I read a lot of subject abaout this problem. but i don't solve a solution for mine.

i create two table : Polluant & Alerte . in Alerte , i have define foreign key the id of polluant. here is the creation code of table :

CREATE TABLE IF NOT EXISTS Polluant (
idPol int(3) PRIMARY KEY AUTOINCREMENT,
nom varchar(10) UNIQUE NOT NULL,
unite varchar(10) NOT NULL
);

CREATE TABLE IF NOT EXISTS Alerte(
idAlerte int(3) PRIMARY KEY AUTO_INCREMENT,
unite varchar(10) NOT NULL,
Max1 int(10) NOT NULL,
Max2 int(10) NOT NULL,
Max3 int(10) NOT NULL,
type boolean NOT NULL,
idPol int(3),
FOREIGN KEY (idPol) REFERENCES Polluant(idPol)
);

Here are entry's:

insert into polluant(nom,unite) values ("testPol","g/m3");
insert into alerte values (1,"test",1,2,3,true,1);
insert into alerte values (2,"autretest",2,4,40,false,1);   !! this one isn't OK

currently trying on mysql but it will go on sqllite asap.

i add a entry in the Polluant table, with id=1. i add a entry in the Alerte table, with idPol =1. no problem.

i add a second entry in the Alerte table , with idPol = 1 . MySQL happily tell me :

1062 - Duplicate entry '1' for key 'idPol'

mhhhh. Why ? it have to be unique in the table polluant ofc and it is, but it doesn't have to be in Alerte, do it? Well , i don't understand the problème, it look fine for me. Do somebody have an idea? Thinqs

È stato utile?

Soluzione 2

don't ask me why, i still don't understand , i erase all the database and create it again i just add a constraint into the create table and it work... thinqs @jmail for your time.

CREATE TABLE IF NOT EXISTS Alerte(
idAlerte int(3) AUTO_INCREMENT,
unite varchar(10) NOT NULL,
Max1 int(10) NOT NULL,
Max2 int(10) NOT NULL,
Max3 int(10) NOT NULL,
type boolean NOT NULL,
idPol int(3),
PRIMARY KEY(idAlerte),

CONSTRAINT fk_pol FOREIGN KEY (idPol) REFERENCES Polluant(idPol)

);

Altri suggerimenti

your referring the Polluant table, so your insert value must be not repeated value

FOREIGN KEY (idPol) REFERENCES Polluant(idPol)

More than likely your column is set to be Unique, and you're trying to input a row with an ID that already exists in your table.

You are probably trying to insert a record with the ID (or some other field) 1 set, while such a record already exists in the table. The field that is the primary key must have a unique value for each record.

Setting the column to auto_increment and not inserting a value when inserting the row (letting it auto populate) would be the best fix. Or you could see the last ID in your table though, and increment it by one for your value

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top