【问题标题】:MySQL: Insert no duplicates for column1 and column2MySQL:为 column1 和 column2 插入不重复项
【发布时间】:2014-04-07 14:49:44
【问题描述】:

如下创建表,其中column1和column2都是外键值。

ID|Column1|Column2|

0 | 1 | 1

1 | 1 | 2

2 | 1 | 2

3 | 2 | 2

我不想在插入时像第 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);

【问题讨论】:

  • 你能改变表结构吗?如果是这样,我建议制作一个唯一的多列索引。请参阅此问题以了解如何做到这一点stackoverflow.com/questions/635937/…
  • MySQL Insert Where query的可能重复
  • 确切地说:如何创建唯一的多列索引?
  • 那么只需让 column1 和 column2 成为唯一键?

标签: mysql insert where jointable


【解决方案1】:

您似乎正在创建一个所谓的连接表,其目的是将 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
 )

如果您这样做,您将无法插入重复值。

【讨论】:

  • 让我试试这个。我认为我会遇到的问题是,如果 column1 已经插入,我不能在 column1 中多次插入值“1”。
  • 您的问题有两行,其中包含“1,2”。
  • 这不起作用,因为我希望 column1 和 colmn2 组合是唯一的,因此 1|1 1|2 1|3 是唯一的,其中 1|1 1|1 1|1|不是。
  • 如何添加:alter table tablename add unique index(column1, column2);对你的陈述?
猜你喜欢
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
相关资源
最近更新 更多