简体   繁体   English

Mysql唯一字段由外键

[英]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. 目前,我的表中只能有一个具有相同值的id_Specialite,但是有没有一种方法可以通过id_Entreprise只将一个唯一的id_Specialite。

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: 为什么不将d_Entrepriseid_Specialite用作ompound/composite Primary Key ,例如:

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

See SQLFiddle Demo 请参见SQLFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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