单表:SQL语句关键字的执行顺序

表和数据:

-- 创建表
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `age` tinyint(4) DEFAULT '0',
  `gender` enum('','') NOT NULL DEFAULT '',
  `salary` decimal(10,2) NOT NULL DEFAULT '2500.00',
  `hire_date` date NOT NULL,
  `dept_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

-- 创建数据
-- 教学部
INSERT INTO `person` VALUES ('1', 'A', '28', '', '53000.00', '2010-06-21', '1');
INSERT INTO `person` VALUES ('2', 'B', '23', '', '8000.00', '2011-02-21', '1');
INSERT INTO `person` VALUES ('3', 'C', '30', '', '6500.00', '2015-06-21', '1');
INSERT INTO `person` VALUES ('4', 'D', '18', '', '6680.00', '2014-06-21', '1');
-- 销售部
INSERT INTO `person` VALUES ('5', 'E', '20', '', '3000.00', '2015-02-21', '2');
INSERT INTO `person` VALUES ('6', 'F', '20', '', '2000.00', '2018-01-30', '2');
INSERT INTO `person` VALUES ('7', 'G', '20', '', '2000.00', '2018-02-27', '2');
INSERT INTO `person` VALUES ('8', 'H', '20', '', '2000.00', '2015-06-21', '2');
-- 市场部
INSERT INTO `person` VALUES ('9', 'I', '21', '', '4000.00', '2014-07-21', '3');
INSERT INTO `person` VALUES ('10', 'J', '22', '', '4000.00', '2015-07-15', '3');
-- 人事部
INSERT INTO `person` VALUES ('11', 'K', '17', '', '5000.00', '2014-06-21', '4');
-- 鼓励部
INSERT INTO `person` VALUES ('12', 'L', '33', '', '1000000.00', '2018-02-21', null);
View Code

SQL语句关键字的执行顺序:

-- 查询:姓名不同人员的最高工资,并且要求工资大于5000元,同时按最大工资进行排序并取出前5条
select name, max(salary)
from person
where name is not null  
group by name
having max(salary)>5000
order by max(salary)
limit 0,5;

在上面的示例中 SQL 语句的执行顺序如下:

  1. 首先执行 FROM 子句,从 person 表 组装数据源的数据
  2. 执行 WHERE 子句,筛选 person 表中 name 不为 NULL 的数据
  3. 执行 GROUP BY 子句,把 person 表按 name 列进行分组
  4. 计算 max() 聚集函数,按 工资 求出工资中最大的一些数值
  5. 执行 HAVING 子句,筛选工资大于 5000 的人员
  6. 执行 ORDER BY 子句,把最后的结果按 Max(工资) 进行排序
  7. 最后执行 LIMIT 子句,进行分页查询

执行顺序:from -> where -> group by -> having -> select -> order by -> limit

原文地址:https://www.cnblogs.com/believepd/p/10439812.html