Mysql – How to speed up an sql query that round trips between two tables

MySQLperformancePHP

These tables are not that big, but the time taken to process this query is long.

What can I do with the following queries to speed up the process taken to return results?

$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

This tables are growing, I'm worried that maintaining them will be a problem if this is already slow.

Best Answer

It's more or less like this...

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