如下面两个查询所示,我们发现它们都很好.然后我很困惑为什么我们应该使用BETWEEN,因为我发现BETWEEN在不同的数据库中的行为与
w3school
SELECT * FROM employees WHERE salary BETWEEN 5000 AND 15000; SELECT * FROM employees WHERE salary >= 5000 AND salary <= 15000;
解决方法
BETWEEN可以帮助避免不必要的重新评估表达式:
SELECT AVG(RAND(20091225) BETWEEN 0.2 AND 0.4) FROM t_source; --- 0.1998 SELECT AVG(RAND(20091225) >= 0.2 AND RAND(20091225) <= 0.4) FROM t_source; --- 0.3199
t_source只是一个具有1,000,000条记录的虚拟表.
当然,BETWEEN更可读.在查询中使用它需要3次才能永远记住语法.
在sql Server和MysqL中,对一个具有非领先’%’的常量的LIKE也是一对> =和< ;:
SET SHOWPLAN_TEXT ON GO SELECT * FROM master WHERE name LIKE 'string%' GO SET SHOWPLAN_TEXT OFF GO |--Index Seek(OBJECT:([test].[dbo].[master].[ix_name_desc]),SEEK:([test].[dbo].[master].[name] < 'strinH' AND [test].[dbo].[master].[name] >= 'string'),WHERE:([test].[dbo].[master].[name] like 'string%') ORDERED FORWARD)
但是,LIKE语法更清晰.