doucan1996 2013-05-02 19:44
浏览 23
已采纳

在SQL中检查行的简单方法,如果不存在则添加? (超过100k行)

I have a script that adds about 100,000 entries to SQL if it doesn't exist. But it normally takes about 30 hours to fully check each row and add if it doesnt exist. Is there an easier way to do this?

my code currently uses a for Loop, within the loop is this.

$query = mysql_query("SELECT EXISTS (SELECT * FROM linkdb WHERE link='$currentlink')");

if (mysql_result($query, 0) == 1){

}else{
  $qry = "INSERT INTO linkdb(link,title) VALUES('$link','$title')";
  $result = @mysql_query($qry);

}

the code above takes very long time because it has to normally go through thousands of entries. If I don't check the table first using SELECT EXIST and use only INSERT INTO, 90,000 entries are added within 1 min. But that adds duplicate entries of the same row.

Please give me some advice on what I could do. These rows need to be updated almost everyday.

  • 写回答

3条回答 默认 最新

  • douling8772 2013-05-02 19:48
    关注

    You're looking for ON DUPLICATE KEY UPDATE. Add an index on link and then:

    INSERT INTO linkdb(link,title) VALUES('$link','$title') ON DUPLICATE KEY UPDATE link=link;
    

    With that said, you should not be using ext/mysql since it is deprecated. Instead look into PDO or mysqli. It would be much better to use parametrized queries for this to prevent SQL injection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)