仅当两个列不重复时才插入


INSERT only if both colomns are not duplicate

DELETE FROM RelationsAuthors WHERE MainId = :MainId AND AuthorId NOT IN (:authorarray)

上面的代码将删除任何不在authorarry中并且MainId等于特定值的内容。

删除后,如果authoarray的值不存在,我想将它们插入数据库而不会出现任何错误。

*使用foreach $_POST['AuthorId']

INSERT INTO RelationsAuthors (Id,MainId,AuthorId) VALUES('',:MainId,:AuthorId)

但是,我想在我的代码中添加我只需要插入不存在的地方(MainId = :MainId AND AuthorId = :AuthorID)。我该怎么做?

首先,在两个字段上创建一个唯一的索引,以便数据库将为您防止重复:

create unique index idx_RelationsAuthors_MainId_AuthorId on RelationsAuthors(MainId, AuthorId);
然后,如果您有

重复项,insert将失败并显示错误。 您可以通过几种方式忽略此错误。 我的首选方法是:

INSERT INTO RelationsAuthors (MainId, AuthorId)
     VALUES(:MainId, :AuthorId)
     ON DUPLICATE KEY UPDATE MainId = VALUES(MainId);

这将专门忽略重复键错误,但其他问题仍会生成错误(如果适用)。 请注意,我删除了第一列。 我从语法中猜测它是一个自动递增的 id,所以你根本不需要把它包含在 insert 语句中。