I would like to know if this query can run faster or how to make it faster if possible.
$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.' '. $total .'</a></li>';
}
echo '<li class="spaceIN"></li><li class="letter">A</li>';
I make a copy of this script and paste it like 100 times and it is really slow loading after doing that.
Like this
select sum(title LIKE '%Cars%') as cars,
sum(title LIKE '%Bikes%') as bikes
from videos
You could replace your inline queries in the select
list with sum
functions over boolean expressions:
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
Along with the SQL suggestions in other answers - how about rather than having that query run every time someone visits that page (assuming that's what happens) - instead store counts in the database and have a Cron job run the script to update them at regular intervals in the background. Then query the stored count on that page - which will obviously be considerably faster
Add a category column, int or enum, depends on how often you add/change categories. You could use:
SELECT COUNT(*) as c, category FROM videos GROUP BY category;
then. Waaaay better to have defined categories than having to do string stuff on every query. Also '%' in the beginning is slow as hell as it can't use indexes.