【问题标题】:How best to upload data to a database table and prevent duplicate entries?如何最好地将数据上传到数据库表并防止重复条目?
【发布时间】:2012-02-03 19:36:34
【问题描述】:

我正在尝试防止表中出现重复副本。我正在寻找整行是另一行的副本的重复项。如果一行的一个元素是另一行的某些内容的副本,那不是问题。例如,如果名称在多个字段中重复,那没关系,但如果每个附加字段与另一个条目相同,那么我想阻止我的程序添加条目。这是我要尝试的:

if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE field1 = '$field1',field2 =     '$field2', field3 = '$field3',field4 = '$field4'"))){
// send some message if entry is within table
} else {
// add unique entry to the table if field is not there
}

上面的代码是否会搜索并检查所有 4 个值是否都在每一行中,或者是否所有 4 个值都位于每列中的某个位置但不一定在每一行中?

【问题讨论】:

    标签: php sql


    【解决方案1】:

    添加唯一键:

    ALTER TABLE table ADD UNIQUE( field1);
    

    而不是使用插入到 ignore 关键字:

    INSERT IGNORE INTO table ...;
    

    这样:

    • 您将只有一个对数据库的查询
    • 不会触发错误
    • 数据库不会出现重复(由数据库保证)

    这是很好的阅读:INSERT IGNORE or INSERT WHERE NOT IN

    【讨论】:

    • 这样会不会使表格不会添加任何与 field1 同名的条目?我可以更改上述内容,以便其他字段也被考虑在同一行中吗?
    • @Stagleton 你对UNIQUE KEYS 了解多少?他们确保数据在表中是唯一的,如果您创建索引UNIQUE (name),您可以只插入每个名称一次(另一个尝试创建失败)。在UNIQUE (category_id, product_id)上创建时,可以插入(1,1), (1,2), (2,2),但是重新插入(1,1)会报错。当您使用INSERT IGNORE 时,不会产生错误,查询会静默停止。您也可以使用ON DUPLICATE(请参阅我答案末尾的链接)。
    • 我知道的还不够。我回家后会试试的。感谢您的帮助。
    • A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. 这是 mysql 手册提供和发现的所有内容(Jakub Vrana 前段时间写了一篇关于使用唯一键的完美文章php.vrana.cz/vyuziti-unikatnich-klicu-v-databazi.php 但它是捷克语但你可能会理解它谷歌翻译的帮助不大)。
    • 这似乎无法正常工作。除了日期之外,我有唯一的字段,但由于日期字段重复而出现错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2016-07-23
    • 1970-01-01
    • 2019-07-24
    • 2017-08-14
    • 2010-11-29
    相关资源
    最近更新 更多