This query is taking long time to execute. Anybody tell me how to optimize this query?
$sql = '';
$now = time();
$until = $now + 604800;
for ($i=0; $i < 7 ; $i++) {
$dayno = date('N', $now + ($i * 86400));
$sql .= "SELECT p.id, p.iam, p.offertimes, p.fromcity, p.tocity, p.days, p.parcel, p.seats, p.price,
CASE
WHEN days LIKE '%{$dayno}%' THEN
(select unix_timestamp(addtime(timestamp(date(now())+{$i}),time(from_unixtime(deadline)))))
ELSE deadline
END AS deadline,
c1.nameRu AS 'from',
c2.nameRu AS 'to',
c3.nameRu AS 'city'
FROM posts AS p
LEFT JOIN citynames AS c1 ON p.from_id = c1.id
LEFT JOIN citynames AS c2 ON p.to_id = c2.id
LEFT JOIN citynames AS c3 ON p.city_id = c3.id
WHERE p.deadline > {$now} ";
if ($i == 0) {
$sql .= "AND {$now} < (SELECT unix_timestamp(addtime(timestamp(date(now())), time(from_unixtime(deadline))))) ";
}
$sql .= "AND p.days LIKE '%{$dayno}%' UNION ALL ";
}
$sql .= "SELECT p.id, p.iam, p.offertimes, p.fromcity, p.tocity, p.days, p.parcel, p.seats, p.price, p.deadline,
c1.nameRu AS `from`,
c2.nameRu AS `to`,
c3.nameRu AS `city`
FROM posts AS p
LEFT JOIN citynames AS c1 ON p.from_id = c1.id
LEFT JOIN citynames AS c2 ON p.to_id = c2.id
LEFT JOIN citynames AS c3 ON p.city_id = c3.id
WHERE p.deadline > {$now} AND p.days = '' ORDER BY `deadline` ASC";
UPDATED: I have to 2 types of posts 1st is once and departure (e.g 25 march 2015, 7:00 AM), 2nd is regular and departure (e.g. every Monday, Friday, Sunday at 8:AM until 12 April 2015). What i want is: when user search code must convert all regular posts to 1st post type according to name of week day (until next week) but i must keep hours and minutes as old. I save my departure in one field (deadline) for regular posts additional filed (days). Here is my mysql table (short):
offertime|from_id|to_id|via_id|deadline |days
2 | 52| 43| 73|1432036859|1,2,7
1 | 72| 65| 66|1424860459|
2 | 55| 23| 88|1425149999|1,2,3,4,5,6,7
- offertime = 2 (regular)
- offertime = 1 (once)