首页 > 解决方案 > 避免基于另一个列值的列值的 SQL INSERT 重复

问题描述

不确定问题是否很清楚,因此欢迎提出任何建议。

我有下表:

Table1
----------
ID   fk_soc   fk_product   value
1    365      20           654896
2    365      21           654897
3    365      25           654898
4    820      20           114352
5    820      21           114381
6    820      25           114382

如您所见,在第二列中,我可以fk_product为不同的客户 ID 设置相同的号码。但是如何避免fk_product同一客户的重复记录?即避免

Table1
----------
ID   fk_soc   fk_product   value
1    365      20           654896
2    365      20           whatever_here

如果我设置fk_product为唯一,我将无法为其他客户插入记录。记录使用普通 SQL INSERT INTO 插入并来自 HTML 表单:

INSERT INTO Table1 (fk_soc, fk_distributor_product_code, fk_product)
VALUES (
    ' . $this->db->escape($this->fk_line) . ',
    ' . $this->db->escape($this->value) . ',
    ' . $this->db->escape($this->fk_product) . '
)

我试过使用:

INSERT INTO Table1 (fk_soc, fk_distributor_product_code, fk_product)
VALUES (
    ' . $this->db->escape($this->fk_line) . ',
    ' . $this->db->escape($this->value) . ',
    ' . $this->db->escape($this->fk_product) . '
)
    WHERE NOT EXISTS (
        SELECT ' . $this->db->escape($this->fk_product) . '
        FROM table WHERE fk_soc= ' . $this->db->escape($this->fk_soc) . '

但是这种方式没有插入记录

标签: phpmysqlinsertduplicates

解决方案


推荐阅读