mysql中的限定谓词和null
1.说明
mysql中的限定我也是后来才了解,但是之前一直没用
几个常用的限定谓词
all , some , any
在子查询中会用
2.准备测试的数据库脚本
CREATE TABLE Class_A
(name VARCHAR(16) PRIMARY KEY,
age INTEGER,
city VARCHAR(16) NOT NULL );
CREATE TABLE Class_B
(name VARCHAR(16) PRIMARY KEY,
age INTEGER,
city VARCHAR(16) NOT NULL );
INSERT INTO Class_A VALUES('布朗', 22, '东京');
INSERT INTO Class_A VALUES('拉里', 19, '埼玉');
INSERT INTO Class_A VALUES('伯杰', 21, '千叶');
INSERT INTO Class_B VALUES('齐藤', 22, '东京');
INSERT INTO Class_B VALUES('田尻', 23, '东京');
INSERT INTO Class_B VALUES('山田', NULL, '东京');
INSERT INTO Class_B VALUES('和泉', 18, '千叶');
INSERT INTO Class_B VALUES('武田', 20, '千叶');
INSERT INTO Class_B VALUES('石川', 19, '神奈川');
3.测试all后面的列中有null
需求:
将上述表格的空值填为20,查询”比B班住在东京的所有学生年龄都小的A班学生“
MariaDB [test]> select * from class_a where age<all (select age from class_b where city='东京');
Empty set (0.000 sec)
修改后的sql(正确)
select * from class_a where age<all (select age from class_b where city='东京' and age is not null);
+------+------+------+
| name | age | city |
+------+------+------+
| 伯杰 | 21 | 千叶 |
| 拉里 | 19 | 埼玉 |
+------+------+------+
4.限定谓词和极值函数不是等价的
1.使用限定谓词all查询
--使用限定谓词all查询
mysql> select * from class_a
-> where age<all(select age from class_b where city='东京');
Empty set (0.00 sec)
2.使用极值函数
--使用极值函数
mysql> select * from class_a
-> where age<(select min(age) from class_b where city='东京');
+--------+------+--------+
| name | age | city |
+--------+------+--------+
| 伯杰 | 21 | 千叶 |
| 拉里 | 19 | 埼玉 |
+--------+------+--------+
5.结论
1.极值函数在统计时会把null的数据排除掉
2.all谓词,不会把null值的数据排除掉
3.null和all谓词不是等价的情况
all谓词里面查询的列中有null值
all谓词里面查询的列是一个空集