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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度