我正在读取一个很长的文本文件,其中每一行都由一个ID、groupID和其他数据组成。每个ID可以与许多groupID相关联(第1、2、3行),并且每个ID groupID组合可以与许多数据相关联(第一、第二、第三行)。
JWOFJ903JCKDF8O | groupID-22 | some data
JWOFJ903JCKDF8O | groupID-33 | same ID as above, but different groupID and data
JWOFJ903JCKDF8O | groupID-33 | same ID and groupID as above, but different data
...
DF8#CKJ90JJ3WOF | groupID-22 | some data
...
我将这些数据移动到数据库中,因此我有一个ID表(无ID重复)、一个ID和groupID表(没有ID groupID重复)以及一个引用ID groupID表的数据表。
因此,要在数据库中插入1行,我首先检查ID表中是否不存在此ID,然后插入它。然后检查ID groupID组合是否不存在于ID groupID表中,然后插入。最后,插入此ID groupID ID下的数据。
does this $id exist in the IDs table
if($id doesn't exist in the IDs table){
insert a new ID()
save()
}
does this ID-groupID combo exist in the ID-groupID table
if(doesn't exist){
create new id-groupid combo
}
does this data exist under the third table in association with this id-groupid combo
if(doesn't exist){
insert it
}
问题是,由于文件非常大(100000行),这个过程需要数小时才能完成。我能做些什么来优化我的推进查询吗?还是改进数据库的设计?
您应该使用PDO。PDO为您提供了一些性能和安全性方面的改进。此外,PDO和MySQLi模块支持事务,这很可能是您想要的。
如果只执行INSERT/UPDATE/SELECTS,事务将被缓存并一次性执行,而不是每次调用。这非常适合有循环的场景。
示例:
$pdo = new PDO(...);
$pdo->beginTransaction();
foreach($array as $ar){
$pdo->query('INSERT INTO...');
}
$pdo->commit();
它指向一篇关于Propel优化的文章,以进行大规模插入。这是法语,但很容易理解。