php - 通过避免对所有条目进行单一 SELECT 来列出不会导致重复的 INSERT

标签 php mysql sql

我将产品插入 table使用INSERT INTO DBXY.table (category, title, description, cost, supplier) VALUES (?,?,?,?,?)使用准备好的语句。

supplier是一个数字。

表中可能已经包含具有相同类别、标题、描述、成本和供应商的条目。我想知道将插入哪些条目,即那些不重复的条目。我可以做一个

SELECT * FROM table WHERE (category = PHPcat) AND (title = PHPtitle) AND....

对于每个条目,如果结果行数大于 0,则我们有一个重复条目,并且没有新条目。但我认为这种方法对于 6000 及更多条目来说是有缺陷的。有没有办法立即执行此操作,以便我获得包含所有新条目的输出,而无需立即插入它们?

最佳答案

正确的方法是在表上定义唯一索引(这相当于约束):

create unique index table_allcols on table(category, title, description, cost, supplier);

您也可以在插入中执行此操作:

INSERT INTO DBXY.table (category, title, description, cost, supplier)
    select category, title, description, cost, supplier
    from (select ? as category,? as title, ? as description, ? as cost, ? as supplier) t
    where not exists (select 1
                      from table t2
                      where t2.category = table.category and
                            t2.title = table.title and
                            t2.description = table.description and
                            t2.cost = table.cost and
                            t2.supplier = table.supplier
                     );

编辑:

要查找匹配列表,请创建一个临时表并在它们之间连接:

select tt.*
from temporary_table tt
where not exists (select 1
                  from table t2
                  where t2.category = tt.category and
                        t2.title = tt.title and
                        t2.description = tt.description and
                        t2.cost = tt.cost and
                        t2.supplier = tt.supplier
                 );

关于php - 通过避免对所有条目进行单一 SELECT 来列出不会导致重复的 INSERT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18393554/

相关文章:

sql - 将所有同义词更改为另一个数据库

php - 从选择 MYSQL PHP 中隐藏特定行

php - Laravel 多维数组获取值

javascript - 无法将数据库中的数据与字符串数组进行比较

javascript - 如何在没有 JavaScript 的情况下强制 HTML 元素保持恒定的宽高比?

php - 在选择表单中使用 AJAX

mysql - 加入 Max Row where Col

php - Laravel 原始查询并包含模型关系

mysql - 同步2个数据库

mysql - 查询返回上个月的变化