SQL语句中有多个BETWEEN和LIMIT运算符

时间:2014-11-28 20:48:35

标签: php mysql sql

我正在尝试获得两行的结果集。

这两行是在BETWEEN运算符中指定的时间跨度之间找到的最后一行。

如何实现这一结果?

以下代码不起作用。

SELECT 
DaySum_1+DaySum_2+DaySum_3+DaySum_4+DaySum_5
AS october
FROM   solarenergy
WHERE ((DatumUhrzeit BETWEEN '2014-10-01 01:00:00' AND '2014-10-01 23:00:00') LIMIT 1)
   OR ((DatumUhrzeit BETWEEN '2014-10-02 01:00:00' AND '2014-10-02 23:00:00') LIMIT 1)
ORDER BY DatumUhrzeit DESC

1 个答案:

答案 0 :(得分:1)

您需要执行UNION才能应用两个单独的LIMIT,因为每个查询只能使用一个LIMIT。要使用单个UNION子句,每个()组件必须包含在( SELECT DaySum_1+DaySum_2+DaySum_3+DaySum_4+DaySum_5 AS october FROM solarenergy WHERE DatumUhrzeit BETWEEN '2014-10-01 01:00:00' AND '2014-10-01 23:00:00' ORDER BY DatumUhrzeit DESC LIMIT 1 ) UNION ( SELECT DaySum_1+DaySum_2+DaySum_3+DaySum_4+DaySum_5 AS october FROM solarenergy WHERE DatumUhrzeit BETWEEN '2014-10-02 01:00:00' AND '2014-10-02 23:00:00' ORDER BY DatumUhrzeit DESC LIMIT 1 )

UNION

如果您想保证()产生的两行订单,必须在最后( SELECT DaySum_1+DaySum_2+DaySum_3+DaySum_4+DaySum_5 AS october FROM solarenergy WHERE DatumUhrzeit BETWEEN '2014-10-01 01:00:00' AND '2014-10-01 23:00:00' ORDER BY DatumUhrzeit DESC LIMIT 1 ) UNION ( SELECT DaySum_1+DaySum_2+DaySum_3+DaySum_4+DaySum_5 AS october FROM solarenergy WHERE DatumUhrzeit BETWEEN '2014-10-02 01:00:00' AND '2014-10-02 23:00:00' ORDER BY DatumUhrzeit DESC LIMIT 1 ) /* Global ORDER BY after UNION */ ORDER BY october ASC 组之外应用

{{1}}