Mysql学习MySQL无GROUP BY直接HAVING返回空的问题分析
《Mysql学习MySQL无GROUP BY直接HAVING返回空的问题分析》要点: 有一张表,id是主键,这样的写法可以返回一条记录: “SELECT * FROM t HAVING id=MIN(id);” 但是只是把MIN换成MAX,这样返回就是空了: 代码如下: “SELECT * FROM t HAVING id=MAX(id);” 这是为什么呢? 我们先来做个试验,验证这种情况. 这是表结构,初始化两条记录,然后试验: 代码如下: root@localhost : plx 10:25:10> show create table t2G *************************** 1. row *************************** ?????? Table: t2 Create Table: CREATE TABLE `t2` ( ? `a` int(11) DEFAULT NULL, ? `id` int(10) unsigned NOT NULL AUTO_INCREMENT, ? PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 root@localhost : plx 10:25:15> select * from t2; +------+----+ | a??? | id | +------+----+ |??? 1 |? 1 | |??? 1 |? 3 | +------+----+ 2 rows in set (0.00 sec) root@localhost : plx 10:25:20> SELECT * FROM t2 HAVING id=MIN(id); +------+----+ | a??? | id | +------+----+ |??? 1 |? 1 | +------+----+ 1 row in set (0.00 sec) root@localhost : plx 10:25:30> SELECT * FROM t2 HAVING id=MAX(id); Empty set (0.00 sec) 初看之下,好像真的是这样哎,怎么会这样呢?我再试一下,把a字段改一个为10,然后试下a字段:MYSQL入门 代码如下:root@localhost : plx 10:26:58> select * from t2; +------+----+ | a??? | id | +------+----+ |?? 10 |? 1 | |??? 1 |? 3 | +------+----+ 2 rows in set (0.00 sec) root@localhost : plx 10:28:20> SELECT * FROM t2 HAVING a=MAX(a); +------+----+ | a??? | id | +------+----+ |?? 10 |? 1 | +------+----+ 1 row in set (0.00 sec) root@localhost : plx 10:28:28> SELECT * FROM t2 HAVING a=MIN(a); Empty set (0.00 sec) 我擦,这回MAX能返回,MIN不能了,这又是为啥呢?MYSQL入门 旁白 root@localhost : plx 10:25:48> SELECT * FROM t2 GROUP BY NULL; +------+----+ | a??? | id | +------+----+ |?? 10 |? 1 | +------+----+ 1 row in set (0.00 sec) 也就是说,GROUP BY NULL 以后,只会有一个分组,里面就是第一行数据. root@localhost : plx 10:26:58> select * from t2; +------+----+ | a??? | id | +------+----+ |?? 10 |? 1 | |??? 1 |? 3 | +------+----+ 2 rows in set (0.00 sec) root@localhost : plx 10:27:04> SELECT * FROM t2 GROUP BY NULL; +------+----+ | a??? | id | +------+----+ |?? 10 |? 1 | +------+----+ 1 row in set (0.00 sec) root@localhost : plx 10:30:21> SELECT MAX(a),MIN(a),MAX(id),MIN(id) FROM t2 GROUP BY NULL; +--------+--------+---------+---------+ | MAX(a) | MIN(a) | MAX(id) | MIN(id) | +--------+--------+---------+---------+ |???? 10 |????? 1 |?????? 3 |?????? 1 | +--------+--------+---------+---------+ 1 row in set (0.00 sec) 是不是发现问题了? root@localhost : plx 11:29:49> SELECT MAX(a),MIN(id) FROM t2 GROUP BY a; +--------+--------+---------+---------+ | MAX(a) | MIN(a) | MAX(id) | MIN(id) | +--------+--------+---------+---------+ |????? 1 |????? 1 |?????? 3 |?????? 3 | |???? 10 |???? 10 |?????? 5 |?????? 5 | +--------+--------+---------+---------+ 2 rows in set (0.00 sec) GROUP BY NULL时MAX/MIN的行为,是这个问题的本色,所以啊,尽量使用标准语法,玩花样SQL之前,一定要搞清楚它的行为是否与理解的一致.MYSQL入门 欢迎参与《Mysql学习MySQL无GROUP BY直接HAVING返回空的问题分析》讨论,分享您的想法,编程之家PHP学院为您提供专业教程。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |