如何使此查询运行得更快

时间:2014-10-04 17:29:57

标签: php mysql performance select count

我想知道此查询是否可以更快地运行,或者如果可能的话如何使其更快。

$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次,这样做之后加载速度非常慢。

4 个答案:

答案 0 :(得分:4)

喜欢这个

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

答案 1 :(得分:1)

除了其他答案中的SQL建议之外 - 每次有人访问该页面时都会运行该查询(假设发生了什么) - 而不是在数据库中存储计数并让Cron作业运行脚本来更新它们在后台定期。然后查询该页面上存储的计数 - 这显然会快得多

答案 2 :(得分:0)

您可以使用select列表替换布局表达式中sum列表中的内联查询:

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

答案 3 :(得分:0)

添加类别列,int或enum,取决于您添加/更改类别的频率。你可以使用:

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

然后。 Waaaay最好定义类别而不是每个查询都要做字符串。还有&#39;%&#39;在开始时很慢,因为它不能使用索引。