如何减少sql的使用时间?

时间:2016-04-27 04:47:37

标签: sql sqlite

我是使用sql的初学者,在sqlite db中有两个名为photo和album的表,每个都有8万行data.now我想得到每个图片的forder信息,我写sql:

SELECT *, album.RowId 
FROM photo,album 
WHERE photo.Path=album.Path 
    AND (photo.ThumbnailPath > '' or photo.Duration > 0) 
    AND photo.IsValid=1  
GROUP BY FolderPath 
ORDER BY Date DESC 
LIMIT 201

我使用SQLiteStudio执行sql字符串取0.3秒。但是当我写c代码时使用

gettimeofday(&onestart,NULL);
while (SQLITE_ROW == sqlite3_step(stmt)) {
  gettimeofday(&onestop,NULL);
  double onewhile = (onestop.tv_sec - onestart.tv_sec)*1000000 + onestop.tv_usec - onestart.tv_usec;
  SYSLOG(WARNING) << "one while taken " << onewhile / 1000.0 << " haos";
  onestart = onestop;
  std::cout<<"getAlbumList count is "<<result.size() <<std::endl;
  shared_ptr<BackupFileMetadata> metadata;
  try
    {
     metadata.reset(new BackupFileMetadata);
     unsigned index = fillBasicMetadata(*metadata, stmt);
     metadata->setThumbPath((const char *) sqlite3_column_text(stmt, index++));
     metadata->isProcessed_ = sqlite3_column_int(stmt, index++) == 1;
     metadata->setPath((const char *) sqlite3_column_text(stmt, index++));
     metadata->setName((const char *) sqlite3_column_text(stmt, index++));
     metadata->setFolderPath((const char *) sqlite3_column_text(stmt, index++));
     metadata->rowId = sqlite3_column_int64(stmt, index++);

   }
   catch(...)
   {
     SYSLOG(ERROR)<<"getAlbumPhotos fill data ERROR!";
   }

  result.push_back(*metadata);
}

sqlite3_finalize(stmt);

花时间:

one while taken 5241.04 ms
one while taken 0.778 ms
one while taken 0.555 ms
one while taken 0.536 ms
one while taken 0.528 ms
one while taken 0.62 ms
one while taken 0.607 ms
one while taken 0.626 ms
one while taken 0.589 ms
one while taken 0.559 ms
one while taken 0.538 ms
one while taken 0.531 ms
one while taken 0.524 ms
one while taken 0.512 ms
one while taken 0.522 ms
one while taken 0.524 ms
one while taken 0.522 ms
one while taken 0.631 ms
one while taken 0.606 ms
one while taken 0.544 ms
one while taken 0.528 ms

获取200行数据需要5秒钟!

我想知道为什么?我怎样才能缩短我的课程时间?

http://i.stack.imgur.com/jYNmZ.png

0 个答案:

没有答案