I am logging information from a threads page on my forum, in 4 days there has been nearly 400,000 entries and one SQL query is using 12 seconds, i need help to reduce the query run time if possible or use php to calculate the guests views for each thread_id
I have the following mysql Table and Columns
thread_count
count_id thread_id user_id timestamp ip_address
I have manged to get the weekly stats in 0.2 seconds for threads with over 100 views using this query
SELECT thread_id, timestamp, user_id, COUNT(thread_id) AS cnt FROM thread_count GROUP BY thread_id HAVING COUNT( thread_id) >100 AND timestamp > UNIX_TIMESTAMP() - 24 * 3600 * 7 ORDER BY cnt DESC
The problem is when I try to run this query to find out how many guests views there has been
$guestcount = SELECT user_id, thread_id, COUNT(user_id) AS cntg FROM thread_count WHERE user_id =0 AND thread_id = ".$array['thread_id']."
That is run in a while loop from the first query
This second query takes 12.9 seconds to run
This is the while loop from the php code, its vbulletin so might look strange
while ($array = $db->fetch_array($threadsql)){
$thread_title = $db->fetch_array($vbulletin->db->query_read("SELECT title FROM thread WHERE threadid = ".$array['thread_id'].""));
// $guestcount = $db->fetch_array($vbulletin->db->query_read("SELECT user_id, thread_id, COUNT(user_id) AS cntg FROM " . TABLE_PREFIX . "thread_count WHERE user_id =0 AND thread_id = ".$array['thread_id'].""));
$weekly .= '<tr><td><a href="showthread.php?t='.$array['thread_id'].'">'.$array['thread_id'].'</a></td>
<td>'.$array['cnt'].' </td> <td><a href="showthread.php?t='.$array['thread_id'].'">'.$thread_title[title].'</a></td><td>Username Here</td> <td>'.$guestcount[cntg].'</td> </tr>';
}
Basically guests hits are stored as 0 in the user_id column, I did try this and not use the 12 second query but it just shows me 0
foreach($array as $guest){
if ($array[user_id] = 0 && $thread[thread_id] = $array[thread_id])
$guestcount = count($guest);
}