时间:2021-07-01 10:21:17 帮助过:10人阅读
本文把重点放在一些不太常见的MySQL数据比较函数和运算符上,讨论它们可以被如何运用在应用程序里比较表格字段里的字符串、数字和日期/时间或者用户提供的值。
BETWEEN
BETWEEN运算符是测试在某个范围内是否存在一个数值或者日期值的有用方式。这个运算符接受两个参数——最大值和最小值,并测试所提供的值是否在这两个值的范围之内。如果在这个范围之内,运算符就返回一个布尔值——真;否则,它就返回一个伪值。下面就是一个例子:
mysql> SELECT 2350 BETWEEN 100 AND 10000;
+----------------------------+
| 2350 BETWEEN 100 AND 10000 |
+----------------------------+
| 1 |
+----------------------------+
1 row in set (0.18 sec)
下面两个例子用到了日期值:
mysql> SELECT 20060405 BETWEEN 20060101 AND 20070101;
+----------------------------------------+
| 20060405 BETWEEN 20060101 AND 20070101 |
+----------------------------------------+
| 1 |
+----------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT 20060405 BETWEEN 20060101 AND 20060401;
+----------------------------------------+
| 20060405 BETWEEN 20060101 AND 20060401 |
+----------------------------------------+
| 0 |
+----------------------------------------+
1 row in set (0.00 sec)
GREATEST和LEAST
GREATEST和LEAST运算符为判断一组数字或者时间值中最大和最小值提供了一个便捷的途径。你一看名字就知道这两个运算符的作用——下面是一个对一组日期使用GREATEST运算符的例子:
mysql> SELECT GREATEST(20000601, 20000529, 20000604);
+----------------------------------------+
| GREATEST(20000601, 20000529, 20000604) |
+----------------------------------------+
| 20000604 |
+----------------------------------------+
1 row in set (0.00 sec)
而下面是一个对一组数值使用LEAST运算符的例子:
mysql> SELECT LEAST(100, 200, 50, -6, -73, 1000);
+------------------------------------+
| LEAST(100, 200, 50, -6, -73, 1000) |
+------------------------------------+
| -73 |
+------------------------------------+
1 row in set (0.03 sec)