我正在使用Java PreparedStatement
在查询的开始时间和结束时间中设置两个参数。但是在查询中,我需要在两个地方使用它。我可以输入一些查询变量或缩短请求时间吗?
SELECT * FROM publicutilities.orders
WHERE (works_begin between '2019-05-26 09:00:00' and '2019-05-26 14:00:00' OR works_end between '2019-05-26 09:00:00' and '2019-05-26 14:00:00')
类似这样的东西:
SELECT * FROM publicutilities.orders
VARIABLE begin_time = ?
VARIABLE end_time = ?
WHERE (works_begin between begin_time and end_time OR works_end between begin_time and end_time)
答案 0 :(得分:0)
遵循本教程http://www.mysqltutorial.org/mysql-variables/
我认为您的SQL查询应如下所示:
SET @begin_time := '2013-01-17 00:00:00';
SET @end_time := '2013-01-17 00:00:00';
SELECT * FROM publicutilities.orders
WHERE (works_begin between @begin_time and @end_time OR works_end between @begin_time and @end_time)
我在mysql服务器上尝试过它,并且可以正常工作。希望它也对您有用。
答案 1 :(得分:0)
使用SET @var_name := <value>
来标识SQL中的别名。
重写代码,
SET @begin_ts := '2019-05-26 09:00:00'
SET @end_ts := '2019-05-26 14:00:00'
ELECT * FROM publicutilities.orders
WHERE (works_begin between @ begin_ts and @ end_ts OR works_end between @begin_ts and @end_ts)