简体   繁体   中英

MySql unique field by foreign key

Im Not sure if this question already been asked, because I think my question is not really clear...

Let say i have this table :

CREATE TABLE IF NOT EXISTS EntrepriseSpecialites
(
    id_EntrepriseSpecialite INT AUTO_INCREMENT PRIMARY KEY
    ,id_Entreprise INT
    ,id_Specialite INT UNIQUE
);

At the moment, i can only have one id_Specialite with the same value in my table, but does there is a way to only an unique id_Specialite by id_Entreprise.

Example :

    id_EntrepriseSpecialite | id_Entreprise | id_Specialite
    1 | 1 | 1
    2 | 2 | 1
    3 | 2 | 4
    4 | 2 | 1 <- ops id_Entreprise 2 already have the id_Specialite 1
    5 | 3 | 1

Why not make d_Entreprise and id_Specialite as your c ompound/composite Primary Key , like:

CREATE TABLE IF NOT EXISTS EntrepriseSpecialites
(
 id_Entreprise INT
 ,id_Specialite INT
 , PRIMARY KEY (id_Entreprise, id_Specialite)
);

See SQLFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM