有没有办法在PHP中优化这个mysql代码?

时间:2015-01-10 16:11:53

标签: php mysql arduino

SELECT tblstud.studid,
       tblsched.ip
FROM tblstud
LEFT JOIN tblstudsched ON (tblstud.studid=tblstudsched.studid)
LEFT JOIN tblsched ON (tblstudsched.schedid=tblsched.schedid)
WHERE tblstud.rfidid='".$rfid."'
  AND tblsched.ip='".$ip."'
  AND EXISTS
    (SELECT tblsched.schedid
     FROM tblsched
     INNER JOIN tblstudsched
     WHERE tblstudsched.schedid=tblsched.schedid
       AND NOW() BETWEEN tblsched.timein AND tblsched.timeout)

这是我的代码到目前为止,它的设计是在Arduino微控制器向PHP发送数据之后完成的。在接受另一个数据之前,IT需要大约8秒钟。我还没有检查过Arduino方面,但我认为当我做另一个不同的mysql查询时,它的速度已经足够快了,但是这个查询比上面的查询要短。

表格在Inno DB中,但我稍后会尝试MyISAM,因为后者是最好的,因为读数多于添加数据。

数据类型为Varchar,范围从每个3-30个字符开始。

我对我正在使用的笔记本电脑的速度也很有信心。

1 个答案:

答案 0 :(得分:2)

这是您的查询:

SELECT tblstud.studid, tblsched.ip
FROM tblstud LEFT JOIN
     tblstudsched
     ON (tblstud.studid = tblstudsched.studid) LEFT JOIN
     tblsched
     ON (tblstudsched.schedid = tblsched.schedid)
WHERE tblstud.rfidid = '".$rfid."' AND tblsched.ip = '".$ip."' AND
      EXISTS (SELECT tblsched.schedid
              FROM tblsched INNER JOIN
                   tblstudsched
                   ON tblstudsched.schedid = tblsched.schedid AND
                      NOW() BETWEEN tblsched.timein AND tblsched.timeout
              );

首先,外部查询中的LEFT JOIN是不必要的,因为WHERE条件只是将其转换为INNER JOIN。其次,您的EXISTS看起来很可疑。它只是想查看数据中是否有任何活动的时间表。因此,它要么全部过滤掉,要么一无所获。您有可能打算:

SELECT tblstud.studid, tblsched.ip
FROM tblstud INNER JOIN
     tblstudsched
     ON (tblstud.studid = tblstudsched.studid) INNER JOIN
     tblsched
     ON (tblstudsched.schedid = tblsched.schedid)
WHERE tblstud.rfidid = '".$rfid."' AND tblsched.ip = '".$ip."' AND
      EXISTS (SELECT 1
              FROM tblsched
              WHERE tblstudsched.schedid = tblsched.schedid AND
                    NOW() BETWEEN tblsched.timein AND tblsched.timeout
              );

但是,我怀疑您希望计划符合where条件。如果是这样,这可能是您想要的逻辑:

SELECT tblstud.studid, tblsched.ip
FROM tblstud LEFT JOIN
     tblstudsched
     ON (tblstud.studid = tblstudsched.studid) LEFT JOIN
     tblsched
     ON (tblstudsched.schedid = tblsched.schedid)
WHERE tblstud.rfidid = '".$rfid."' AND tblsched.ip = '".$ip."' AND
      NOW() BETWEEN tblsched.timein AND tblsched.timeout;

如果这种可疑情况属实,那么您需要tblstud(rfidid, studid)tblsched(schedid, ip, timein, timeout)以及tblstudsched(studid, schedid)上的索引。请注意,这些是具有多个键的复合索引。