有没有办法优化 php 中的 mysql 代码?

Is there a way to optimize this mysql code in php?

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 之后完成。在接受另一个数据之前,我需要大约 8 秒的时间。我没有检查 Arduino 方面,但我认为当我进行另一个不同的 mysql 查询时它已经足够快了,但那个查询比上面的查询相对短。

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

数据类型为 Varchar,范围从 3-30 个字符不等。

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

这是您的查询:

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) 上建立索引。请注意,这些是具有多个键的复合索引。