1

My site is loading very slowly, it's only a single page that is loading slow, and I suspect it is because of a MySQL query being sent to the database. How can I speed it up?

$depquery = "SELECT * FROM phpvms_schedules 
WHERE code = 'FE'
AND locate(dayofweek(convert_tz(now(),'+1:00','+0:00'))-1,".TABLE_PREFIX."schedules.daysofweek)>0
AND phpvms_schedules.enabled = '1'
ORDER BY deptime ASC";

The query is basically working to extract information into a 'Departure Board' table. The table is sorted by deptime, and it displays results from current time onwards. However, I also want it to go back at least 4 records, to 4 flights before current time.

To clarify, let me give you an example:

It's now 15:25. Because of if(($flight->deptime) >= $time) and if($count < 15) and inside a foreach it will display 15 records on and after that time. However, I want to also travel back 4 records, so it finds last 4 records before 15:25. Is this possible?

Basically, I want to search up and down around the current time.

4

1 回答 1

2

你想要一个 UNION,比如:

SELECT * phpvms_schedules 
WHERE code = 'FE' 
AND locate(dayofweek(convert_tz(now(),'+1:00','+0:00'))-1,
     ".TABLE_PREFIX."schedules.daysofweek)>0
AND phpvms_schedules.enabled = '1'
ORDER BY deptime ASC
LIMIT 15
UNION ALL
SELECT * phpvms_schedules 
WHERE code = 'FE' 
AND locate(dayofweek(convert_tz(now(),'+1:00','+0:00'))-1,
     ".TABLE_PREFIX."schedules.daysofweek)<0
AND phpvms_schedules.enabled = '1'
ORDER BY deptime DESC
LIMIT 4

注意我没有猜到你的日期函数,因为我不知道它在做什么。我只是将 > 更改为 < 并将 deptime 上的排序更改为 DESC。(其中一个 < > 可能还需要有一个 = 才不会错过现在的出发时间?)

使用 LIMIT 将在数据库中进行过滤,而不是在听起来像您正在做的代码中进行过滤。这将减少在代码中处理这些信息的开销,并且应该更快。我还将在数据库中对这些结果的 UNION 进行排序,并避免在代码中进行。

编辑

为了完全清楚,这应该处理数据库中的排序:

SELECT tbl* FROM (
SELECT * phpvms_schedules 
WHERE code = 'FE' 
AND locate(dayofweek(convert_tz(now(),'+1:00','+0:00'))-1,
     ".TABLE_PREFIX."schedules.daysofweek)>0
AND phpvms_schedules.enabled = '1'
ORDER BY deptime ASC
LIMIT 15
UNION ALL
SELECT * phpvms_schedules 
WHERE code = 'FE' 
AND locate(dayofweek(convert_tz(now(),'+1:00','+0:00'))-1,
     ".TABLE_PREFIX."schedules.daysofweek)<0
AND phpvms_schedules.enabled = '1'
ORDER BY deptime DESC
LIMIT 4
) as tbl ORDER BY tbl.deptime ASC
于 2013-01-30T15:38:55.667 回答