您好我有以下MySQL查询:
SELECT sensorNumber, rangeStartTime, rangeEndTime, sensorLow, sensorAverage, sensorHigh
FROM rangeData
WHERE rangeStartTime >= 0
AND rangeEndTime <= 43200
AND (sensorNumber = 3)
ORDER BY sensorNumber;
我怎样才能在rangeStartTime和rangeEndTime时间范围之外只抓取1个上一个和下一个值?
所以在英语中这可以说是:“在下午5:00和晚上7:00之间选择所有值,也在下午5:00之前选择下一个值,在晚上7:00之后选择下一个值。 “
我通过查看其他示例尝试以下操作,但它不起作用:
SELECT sensorNumber, rangeStartTime, rangeEndTime, sensorLow, sensorAverage, sensorHigh
FROM rangeData
WHERE rangeStartTime >= 0
AND rangeEndTime <= 43200
AND rangeStartTime < 0 LIMIT 1
AND rangeEndTime > 43200 LIMIT 1
AND (sensorNumber = 3)
ORDER BY sensorNumber;
每个查询都会增加5-10秒的等待时间,所以我想把它变成一个查询。
答案 0 :(得分:2)
你可以通过3个查询的简单联合来做到这一点,原始的一个,一个用于前一个,一个用于下一个:
(SELECT sensorNumber, rangeStartTime, rangeEndTime, sensorLow, sensorAverage, sensorHigh
FROM rangeData
WHERE (rangeStartTime BETWEEN 0 AND 43200) AND (sensorNumber = 3))
UNION
(SELECT sensorNumber, rangeStartTime, rangeEndTime, sensorLow, sensorAverage, sensorHigh
FROM rangeData
WHERE (rangeStartTime < 0) AND (sensorNumber = 3)
ORDER BY rangeStartTime DESC
LIMIT 1)
UNION
(SELECT sensorNumber, rangeStartTime, rangeEndTime, sensorLow, sensorAverage, sensorHigh
FROM rangeData
WHERE (rangeStartTime > 43200) AND (sensorNumber = 3)
ORDER BY rangeStartTime ASC
LIMIT 1)
ORDER BY sensorNumber;
(顺便说一句:由于您只查询了一个ORDER BY
,因此不需要sensorNumber