【问题标题】:check if row exist in the table before adding it in SQL在将行添加到 SQL 之前检查表中是否存在行
【发布时间】:2012-10-30 17:48:20
【问题描述】:

我正在使用 PythonTweepyMySQLdb 模块构建一个 twitter 抓取应用程序

它将获取数百万条推文,因此性能是一个问题 我想在同一个查询中添加之前检查tweet_id是否存在于表中

表架构是:

  *id* |   tweet_id             |     text
  _____|________________________|______________________________
    1  |   259327533444925056   |     sample tweet1
  _____|________________________|______________________________
    2  |   259327566714923333   |     this is a sample tweet2 

我尝试的代码是,但它执行双重查询:

#check that the tweet doesn't exist first
q = "select count(*) from tweets where tweet_id = " + tweet.id
cur.execute(q)
result = cur.fetchone()
found = result[0]
if found == 0: 
q = "INSERT INTO  lexicon_nwindow (tweet_id,text) VALUES(tweet_id,tweet.text)
cur.execute(q)

使 Tweet_id 唯一并仅插入推文,会引发异常并且效率不高吗?

那么用一个查询来实现这一目标的最佳执行方法是什么?

【问题讨论】:

标签: mysql sql mysql-python


【解决方案1】:

如果您将 tweet_id 作为主键(删除字段 Id),您可以使用 INSERT IGNORE 或 REPLACE INTO。 1 解决了 2 个问题。

如果要保留 Id 字段,请将其设置为索引/唯一,并将其​​设置为自动递增。如果我知道 tweet_id 可以用作主键,我会避开这种方法。

希望这会有所帮助。

哈里

【讨论】:

    【解决方案2】:
    #check that the tweet doesn't exist first
    q = "select count(*) from tweets where tweet_id = " + tweet.id
    cur.execute(q)
    result = cur.fetchone()
    found = result[0]
    if found == 0: 
    q = "REPLACE  lexicon_nwindow (tweet_id,text) VALUES(tweet_id,tweet.text)
    cur.execute(q)
    

    【讨论】:

      【解决方案3】:

      使用 INSERT SELECT 而不是 INSERT VALUES 并在您的 SELECT 中添加一个 WHERE 子句来检查您的 tweet.id 是否已经在表中

      q = "INSERT INTO  lexicon_nwindow (tweet_id,text) 
      SELECT " + tweet.id +" ," + tweet.text +" FROM DUAL
      WHERE not exists(select 1 from tweets where tweet_id = " + tweet.id +" ) "
      

      【讨论】:

        【解决方案4】:

        答案是简介,不要推测

        我并不是要不屑一顾。我们不知道最快的是什么:

        • SELECT +(在代码中)条件插入
        • 替换成
        • 插入忽略
        • 在不存在的地方插入选择...)
        • INSERT 并(在代码中)忽略错误

        我们不知道数据速率、重复频率、服务器配置、是否同时有多个写入器等。

        简介,不要猜测。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-15
          • 2022-01-24
          • 2015-03-12
          • 2018-03-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多