我有这个代码,不知怎的,更新是慢的方法! 我使用它来定义我的数据库:
//class for Database
class MyDB extends SQLite3
{
function __construct()
{
$this->open('/database.db');
}
}
//new db - Object
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
而且我有这个代码,它更新数据库并给我begin_time和length:
//BEGIN
$db->exec('BEGIN;');
//prepare update:
$smt2 = $db->prepare("UPDATE users SET username = :username, full_name = :full_name, is_private = :is_private, is_follower = 1, updated_on = :time, was_follower = NULL WHERE user_id = :usernameId");
//bind parameter
$smt2->bindParam(':usernameId', $usernameId);
$smt2->bindParam(':username', $username);
$smt2->bindParam(':full_name', $full_name);
$smt2->bindParam(':is_private', $is_private);
$smt2->bindParam(':time', $time);
//Prepare second update
$smt3 = $db->prepare("UPDATE users SET followed_on = IfNull(followed_on, :time) WHERE user_id = :usernameId");
//bind parameter
$smt3->bindParam(':usernameId', $usernameId);
$smt3->bindParam(':time', $time);
try {
echo "start\n";
$time_begin = time();
echo $time_begin;
//LOOP
foreach ($followers as $follower) {
$usernameId = $follower->getUsernameId();
$username = $follower->getUsername();
$full_name = $follower->getFullName();
$ProfilPicUrl = $follower->getProfilePicUrl();
$is_private = $follower->isPrivate();
//muss 0 sein, aber ist im mom einfach nur '' bei false.
if(strcmp($is_private, 1) !== 0){
$is_private = 0;
}
$time = time();
//Function, which returns rows, how often an entry exists in db (can only be 0 or 1)
$existence = item_exists($db, 'users', 'user_id', $usernameId);
if($existence)
{
//EXECUTE first update
$smt2->execute();
if(!$smt2){
echo $db->lastErrorMsg();
}
//EXECUTE second update
$smt3->execute();
if(!$smt3){
echo $db->lastErrorMsg();
}
}
}
//COMMIT
$db->exec('COMMIT;');
//TIME
$time_diff = time() - $time_begin;
echo "END: ". $time_diff . "\n";
}
catch (Exception $e) {
echo $e->getMessage();
}
正如你所看到的,我已经使用了" BEGIN"和" COMMIT"什么已经给了一个巨大的推动,我也使用"准备"。但是对于包含10300个条目的数组,它仍然需要173秒。 我做了一个测试,在那里我插入一个数字从0到100.000的数组到数据库中,花了8秒!任何想法,是什么让这段代码中的更新语句如此缓慢?
编辑1
正如在建议的评论中,我将两个更新语句合并为一个,现在正在使用
$smt2 = $db->prepare("EXPLAIN UPDATE users SET followed_on = IfNull(followed_on, :time), username = :username, full_name = :full_name, is_private = :is_private, is_follower = 1, updated_on = :time, was_follower = NULL WHERE user_id = :usernameId");
它还需要87秒。这是正常的吗?
编辑2
好的,发现了什么" EXPLAIN QUERY PLAN"和索引是! 所以目前它是一个全表扫描,我的输出是
猜测我会尝试一些索引:)希望这会更快!谢谢0 | 0 | 0 | SCAN TABLE用户
编辑3
天啊!索引之后它现在需要1秒!!!!我不相信,但我认为它是正确的:D