sql语句中的变量使查询挂起

时间:2018-11-24 18:00:56

标签: variables mariadb

以下sql语句可提供应有的功能。在定义的时间范围内的最小值。

select value, datetime from Schuppen 
where (value = (select min(value) from Schuppen 
    where (measure = 'temp') 
    and datetime between '2018-11-01 00:00:00' and '2018-11-02 00:00:00')) 
and datetime between '2018-11-01 00:00:00' and '2018-11-02 00:00:00';

当我使用变量而不是硬编码日期时,该语句将挂起。

set @startdate = cast('2018-11-01 00:00:00' as datetime);   
select value, datetime from Schuppen 
where (value = (select min(value) from Schuppen 
    where (measure = 'temp') 
    and datetime between @startdate and '2018-11-02 00:00:00')) 
and datetime between '2018-11-01 00:00:00' and '2018-11-02 00:00:00';

我想知道为什么该声明不适用于我的maria db版本10.1.26-MariaDB-0 + deb9u1。

通过mysql控制台尝试。

mysql --user=XXXX --password=XXXX Outdoor-Air
...
Your MariaDB connection id is 194
Server version: 10.1.26-MariaDB-0+deb9u1 Debian 9.1

...

MariaDB [Outdoor-Air]> set @startdate = cast('2018-11-01 00:00:00' as datetime);
Query OK, 0 rows affected (0.00 sec)
MariaDB [Outdoor-Air]> select @startdate;
+---------------------+
| @startdate          |
+---------------------+
| 2018-11-01 00:00:00 |
+---------------------+
1 row in set (0.01 sec)

MariaDB [Outdoor-Air]> select value, datetime from Schuppen where (value = (select min(value) from Schuppen where (measure = 'temp') and datetime between @startdate and '2018-11-02 00:00:00')) and datetime between '2018-11-01 00:00:00' and '2018-11-02 00:00:00';

现在语句挂起。

2 个答案:

答案 0 :(得分:1)

SELECT  `value`, `datetime`
    FROM  Schuppen
    WHERE  measure = 'temp'
      AND  `datetime` >= '2018-11-01'
      AND  `datetime` <  '2018-11-01' + INTERVAL 1 DAY
    ORDER BY `value`  ASC
    LIMIT  1;

这应该会帮助:

INDEX(measure, datetime, value)

此公式与您的公式之间可能存在的差异:如果最低值在当天发生多次,则只会显示一行。

答案 1 :(得分:0)

确保两个查询 viz。SETSELECT语句都在同一会话中运行。 @startdate仅在单个会话中持续存在。

您还可以使用CROSS JOIN和派生表将这两个查询转换为单个查询。

SELECT value,
       `datetime`
FROM   Schuppen
CROSS JOIN (SELECT @startdate := cast('2018-11-01 00:00:00' as datetime)) vars 
WHERE  ( value = (SELECT Min(value)
                  FROM   Schuppen
                  WHERE  ( measure = 'temp' )
                         AND `datetime` BETWEEN
                             @startdate AND '2018-11-02 00:00:00') )
       AND `datetime` BETWEEN '2018-11-01 00:00:00' AND '2018-11-02 00:00:00';