0

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

supplier是一个数字。

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

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

对于每个条目,如果结果行数大于 0,那么我们有一个重复的条目并且没有新条目。但我认为这种方法对于 6000 多个条目是有缺陷的。有没有办法一次做到这一点,所以我得到一个包含所有新条目的输出,而不是现在插入它们?

4

1 回答 1

2

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

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

你也可以这样做insert

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
                 );
于 2013-08-23T02:15:11.383 回答