Php

如何加快在兩個表之間往返的 sql 查詢

  • November 29, 2014

這些表並沒有那麼大,但是處理這個查詢所花費的時間很長。

我可以如何處理以下查詢來加快返回結果的過程?

$msc=microtime(true);

$chat_alg = mysqli_query($con, "
   SELECT sid, COUNT(*) as frequency
   FROM plays
   WHERE time > NOW() - INTERVAL 3 DAY && sid != '' 
   GROUP BY sid
   ORDER BY COUNT(*) DESC
") or die(mysqli_error($con));

while($row_chat_alg = mysqli_fetch_array($chat_alg)) {
   $chart_songs[] = $row_chat_alg['sid'];
}

$imploded_songs = implode($chart_songs, ',');

$projects = $dbh->query("
      SELECT * FROM music
      WHERE perms != 'c' && sid IN($imploded_songs) 
      ORDER BY FIELD(sid,$imploded_songs) 
      limit 50
");

$msc=microtime(true)-$msc;
echo ($msc*1000).' milliseconds';

...
Time taken: 9.5310001373291 milliseconds

這些表正在增長,我擔心如果這已經很慢,維護它們將是一個問題。

或多或少是這樣的……

SELECT m.*
    , COUNT(p.sid) frequency
 FROM music m
 JOIN plays p
   ON p.sid = m.sid
WHERE p.time > NOW() - INTERVAL 3 DAY 
  AND p.sid != '' 
  AND m.perms != 'c' 
GROUP 
   BY m.sid
ORDER 
   BY frequency DESC
LIMIT 50

嘗試刪除

ORDER BY COUNT(*) DESC
ORDER BY FIELD(sid,$imploded_songs) 

引用自:https://dba.stackexchange.com/questions/83904