我正在尝试获取两个日期(特别是24小时)之间的值
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN 20190311 AND 20190312
此查询工作正常,但是,我不希望它有一个固定的日期,我已经检查并看到了许多格式,但是似乎都没有用。请帮助
答案 0 :(得分:1)
如果您“只想今天的记录”-一种简单的方法是:
WHERE accnum = '1534610376'
AND DATE(tdate) = CURRENT_DATE()
但是-要利用索引,不应将列包装到函数中。因此,一种有效的方法是
WHERE accnum = '1534610376'
AND tdate >= CURRENT_DATE()
AND tdate < CURRENT_DATE() + INTERVAL 1 DAY
此查询的最佳索引为INDEX(accnum, tdate)
。
答案 1 :(得分:0)
我建议您将日期放在这样的引号之间:
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN '20190311' AND '20190312'
之后,您可以定义用户定义的函数,如下所示:
CREATE FUNCTION BetweenDate(@toCompare VARCHAR(30), @rightDate DATE, @leftDate DATE)
RETURNS TABLE
AS
BEGIN
RETURN (
SELECT *
FROM transactions
WHERE accum = @toCompare AND tdate BETWEEN @rightDATE AND @leftDate
)
END;