1

In this case, how can I use insert ignore to prevent duplicate rows being inserted?

It all on the userId and elmCol

So:

userId | elmCol
----------------
 1     | 1 //Allow
 1     | 2 //Allow
 1     | 3 //Allow
 1     | 1 //Not allowed if inserted again. I've put it in here just for example)
 2     | 1 //Allow
 2     | 2 //Allow
 2     | 3 //Allow
 2     | 1 //Not allowed if inserted again. I've put it in here just for example)

I'm using MySql and MyIsam type tables. Can I do something like this and use insert ignore?

I tried creating primary keys, but cannot use them on all columns.

4

2 回答 2

1

在两列上应用唯一索引。

CREATE UNIQUE  INDEX unique_userId_elmCol    
    ON table1 (userId ,elmCol);

或者,如果您不想在表中插入重复值,而是希望将该值保留在不同的表中。

您可以在表上创建触发器。像这样:

DELIMITER $$
CREATE TRIGGER unique_key_ignore BEFORE INSERT ON table1
FOR EACH ROW BEGIN
  DECLARE c INT;
  SELECT COUNT(*) INTO c FROM table1 WHERE userId = NEW.userId and elmCol = NEW.elmCol;
  IF (c > 0) THEN
    insert into table2 (userId ,elmCol) values ( NEW.userId , NEW.elmCol);
  END IF;
END$$

DELIMITER ;
于 2013-05-24T11:35:52.973 回答
1

使用复合主键: 如何在 SQL 中定义复合主键?

CREATE TABLE yourTable(
  userId NUMERIC,
  elmCol NUMERIC,
  PRIMARY KEY (userId , elmCol)
);

获得复合主键后,您将无法插入重复项。

顺便说一句,您不应该在这种情况下使用唯一索引,因为它们可以为空。查看此链接,为什么不: 主键或唯一索引?

于 2013-05-24T11:36:07.293 回答