我的表EMPLOYEE包含具有字符串数据类型的loaddate列。
在此列中,日期的存储方式类似于
'2019-12-8',
'2019-12-9',
'2019-12-10',
'2019-12-11',
'2019-12-12',
'2019-12-13',
'2019-12-14',
'2019-12-15',
当我在查询下方运行时
SELECT * FROM employee where loaddate between '2019-12-8' and '2019-12-14';
我得到0条记录。但是,当我在查询下方运行时,获取记录但仅从2019-12-10到2019-12-14',尽管表包含8&9的记录
SELECT * FROM employee where loaddate between '2019-12-08' and '2019-12-14';
以上两个查询之间的区别是2019-12-8和2019-12-08。因此,不明白为什么第一个查询不提供任何记录而第二个查询却不提供记录。
答案在于对以下各部分的理解。
1。在操作员功能之间。
BETWEEN Operator : expression BETWEEN lower_bound AND upper_bound
a. In a WHERE clause, compares an expression to both a lower_bound and upper_bound.
b. The comparison is successful if the expression is greater than or equal to the lower_bound, and less than or equal to the upper_bound.
c. If the bound values are switched, so the lower_bound is greater than the upper_bound, does not match any values.
2。使用的数据类型是字符串,但根据文档,运算符之间通常与数字数据类型一起使用。
3。按加载日期排序
显然,升序的值'2019-12-8'大于'2019-12-15'。再插入两个值'2019-12-08'和'2019-12-09',当它们运行相同的查询顺序时,它们将位于顶部,因为它们将小于'2019-12-10'。
SELECT loaddate FROM employee order by loaddate;
'2019-12-10'
'2019-12-11'
'2019-12-12'
'2019-12-13'
'2019-12-14'
'2019-12-15'
'2019-12-8'
'2019-12-9'
SELECT * FROM employee where loaddate between '2019-12-8' and '2019-12-14'; ---zero results because lower_bound('2019-12-8') is the larger value than upper_bound('2019-12-14'). (case c)
SELECT * FROM employee where loaddate between '2019-12-08' and '2019-12-14'; ---getting records from 2019-12-10 to 2019-12-14 because 08 and 09 don't exist.
SELECT * FROM employee where loaddate between '2019-12-08' and '2019-12-9'; ---this will fetch all the data in the sample considering 10 is greater than 08(assuming 08 and 09 are not inserted yet).