简体   繁体   English

使每个外键的mySQL列唯一

[英]Make mySQL column unique for each foreign key

Let's say I have the following column in my database: 假设我的数据库中有以下列:

Item:
id int PRIMARY KEY,
name string,
foreign_id FOREIGN KEY

Is there a way without querying the database before insertion each time, that one foreign key cannot contain two rows with the same name? 有没有一种方法可以在每次插入之前不查询数据库,即一个外键不能包含两个具有相同名称的行?

Sure, you want to add an (unique) index for your foreign key column. 当然,您想为外键列添加一个(唯一的)索引。 The SQL command to add that is 要添加的SQL命令是

ALTER TABLE `mytable`
ADD UNIQUE INDEX `mytable_idx__1` (`foreign_id`);

If I understand correctly, you might want to use the UNIQUE constraint: 如果我理解正确,则可能要使用UNIQUE约束:

CREATE TABLE (
    id          INT PRIMARY KEY
  , name        VARCHAR(50) --or whatever you need
  , foreign_id  INT UNIQUE
    FOREIGN KEY (foreign_id) REFERENCES...
);

As i Understand using FOREIGN KEY (foreign_id) REFERENCES --- will solve it. 当我了解使用FOREIGN KEY(foreign_id)参考时,---将解决它。 And make sure that the always make a unique key of table as foreign key for other table. 并确保始终将表的unique key作为其他表的foreign key

CREATE TABLE profile
( 
  id int NOT NULL PRIMARY KEY,
  name varchar(50),
  FOREIGN KEY (name)
     REFERENCES member (name) 
     ON DELETE CASCADE
     ON UPDATE CASCADE
) ENGINE=InnoDB ;

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

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