mysql注意:

本例测试数据表

CREATE TABLE `test_student` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键自增id',
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '学生名字',
`subject` varchar(10) NOT NULL DEFAULT '' COMMENT '科目',
`score` tinyint(2) unsigned NOT NULL DEFAULT '0' COMMENT '成绩',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('1', '张三', '语文', '80');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('2', '张三', '数学', '56');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('3', '张三', '英语', '38');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('4', '李四', '语文', '40');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('5', '李四', '数学', '65');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('6', '李四', '英语', '42');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('7', '王五', '语文', '61');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('8', '王五', '数学', '32');
INSERT INTO `cnblog`.`test_student` (`id`, `name`, `subject`, `score`) VALUES ('9', '王五', '英语', '90');

1. MySQL中不允许使用where 列别名作为查询条件,是因为MySql中列的别名本来是返回结果的时候才显示的,不在SQL解析时候使用。如果一定要用别名作为查询条件就用having

  例:要查询语文成绩全部及格的学生有哪些?

     如果这里使用别名 写成 

   SELECT name,subject,score as s FROM `test_student` where subject='语文' and s >60;  报错

   正确写法 SELECT name,subject,score as s FROM `test_student` where subject='语文' having s >60;

2. 分组查询各科最大成绩时候,直接 max(score)  + group by  求出的最大值未必对应相应的人,因为,group by默认已每组第一个值列出。

   例:要查询各科成绩最高的同学名称、成绩

   如果直接用 SELECT name,subject,max(score) as max FROM `test_student` group by `subject` 可以查出最高成绩,但最高成绩并没有对应相应的人,如下:

  

  实际上数学成绩最高65 的为李四 ,英语成绩最高90 的是王五, 语文成绩最高80的是张三。

  正确写法:SELECT * from `test_student` where score in(SELECT max(score) as max FROM `test_student` group by `subject`);

  

     或者:SELECT t1.* from `test_student` as t1 join (SELECT max(score) as max FROM `test_student` group by `subject`) as t2 on t1.score=t2.max;

  

原文地址:https://www.cnblogs.com/wgq123/p/6795099.html