创建表如下,其中column1和column2都是外键值。
ID|列1|列2|
0 | 1 | 1
1 | 1 | 2
2 | 1 | 2
3 | 2 | 2
当我插入时,我不希望出现与行 ID #2 相同的重复项。
我想我可以这样插入:
INSERT INTO tablename (column1, column2) VALUES (@last_id_in_col1key,@last_id_in_column2key) <*>
然后我想要这样的东西:
<*> where column1 and column2 are not equal to @last_id_in_col1key and @last_id_in_column2key
有办法将其添加到我的表中还是必须是单独的命令?
alter table tablename add unique index(column1, column2);
最佳答案
您似乎正在创建一个所谓的联接表,其目的是将 table1 中的项目与 table2 中的项目进行多对多关联。
这通常通过两列表来完成。该表中的两列都是主键的一部分。你会这样做:
CREATE TABLE JoinTable (
first_id INT NOT NULL ,
second_id INT NOT NULL ,
PRIMARY KEY (first_id, second_id),
FOREIGN KEY (first_id)
REFERENCES first(first_id)
ON DELETE CASCADE,
FOREIGN KEY (second_id)
REFERENCES second(second_id)
ON DELETE CASCADE
)
执行此操作时,您将无法插入重复值。
关于MySQL:不为第 1 列和第 2 列插入重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22915839/