2014-10-04 77 views
3

我想知道這個查詢是否可以運行得更快,或者如何儘可能地加快查詢速度。如何使這個查詢運行得更快

$result = mysql_query("select 
(select count(1) FROM videos WHERE title LIKE '%Cars%')as Cars, 
(select count(1) FROM videos WHERE title LIKE '%Bikes%') as 'Bikes', 
(select count(1) FROM videos WHERE title LIKE '%Airplanes%') as 'Airplanes', 
(select count(1) FROM videos WHERE title LIKE '%Trucks%') as 'Trucks', 
(select count(1) FROM videos WHERE title LIKE '%Games%') as 'Games'"); 

$row = mysql_fetch_assoc($result); 

foreach($row as $title => $total) 
{ 
    echo '<li> 
<a href="search.php?search='. $title . '&submit= ">'. $title.'&nbsp;&nbsp;'. $total .'</a></li>'; 
} 

echo '<li class="spaceIN"></li><li class="letter">A</li>'; 

我製作了這個腳本的一個副本,並將其粘貼爲100次,這樣做後真的很慢加載。

+0

如果'SELECT'查詢'INSERT' /'UPDATE' /'DELETE'的比例很大,您可以將這些計數器存儲在一個單獨的表中,並在更新'videos'表時更新它們。 – 2014-10-04 17:41:32

回答

4

喜歡這個

select sum(title LIKE '%Cars%') as cars, 
     sum(title LIKE '%Bikes%') as bikes 
from videos 
+0

謝謝你,這是更快。 – Tasos 2014-10-04 21:04:04

0

您可以用sum功能在布爾表達式替換您的嵌入式查詢在select列表:

SELECT SUM (title LIKE '%Cars%') as Cars, 
     SUM (title LIKE '%Bikes%') as 'Bikes', 
     SUM (title LIKE '%Airplanes%') as 'Airplanes', 
     SUM (title LIKE '%Trucks%') as 'Trucks', 
     SUM (title LIKE '%Games%') as 'Games' 
FROM videos 
1

隨着其他答案SQL建議 - 怎麼樣,而不是在每次有人訪問該頁面時都會運行該查詢(假設發生了這種情況) - 而是將計數存儲在數據庫中,並讓Cron作業運行腳本以在後臺定期更新它們。然後查詢該頁面上存儲的計數 - 這顯然會更快

0

添加類別列int或enum取決於您添加/更改類別的頻率。您可以使用:

SELECT COUNT(*) as c, category FROM videos GROUP BY category; 

然後。 Waaaay更好地定義了類別,而不是在每個查詢上都執行字符串填充。另外'%'在開始的時候很慢,因爲它不能使用索引。

+0

謝謝你的光臨。但爲什麼'%'慢,我應該刪除它? – Tasos 2014-10-04 21:06:39

+0

**爲什麼'%'緩慢**好,如果你必須讀一本書中的每個字符來定位每個包含'汽車'的句子,那麼會慢一點,然後翻轉到索引找到CAR? – 2014-10-06 03:31:51