Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在SQL中添加行之前,请检查表中是否存在行_Mysql_Sql_Mysql Python - Fatal编程技术网

Mysql 在SQL中添加行之前,请检查表中是否存在行

Mysql 在SQL中添加行之前,请检查表中是否存在行,mysql,sql,mysql-python,Mysql,Sql,Mysql Python,我正在使用Python、Tweepy和MySQLdb模块构建一个twitter抓取程序 它将获得数百万条推文,因此性能是一个问题 在将tweet_id添加到同一查询中之前,我想检查它是否存在于表中 表架构为: *id* | tweet_id | text _____|________________________|______________________________ 1 | 259327533444925056 |

我正在使用Python
Tweepy
MySQLdb
模块构建一个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唯一,只插入Tweet,会引发异常,也不会有效率


那么,用一个查询实现这一点的最佳方法是什么

如果将tweet_id作为主键(drop field id),则可以使用INSERT IGNORE或REPLACE INTO。在1中解决了2个问题

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

希望这有帮助


Hari

使用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 +" ) "

答案是侧面图,不要猜测

我不是有意轻视你。我们不知道什么是最快的:

  • 选择+(在代码中)条件插入
  • 替换成
  • 插入忽略
  • 插入选择不存在的位置…)
  • 插入和(在代码中)忽略错误
我们不知道数据速率、重复频率、服务器配置、是否同时有多个写入程序等

个人资料,不要猜测。

可能重复的
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 +" ) "