sql-DML-查询语句(单个结果集)

  查询分为两部分,组成结构,执行步骤。

1、组成结构

  查询语句由7部分组成:select, from, where, group by, having, order by, limit

 1.1  select

  select部分,有以下几种类型。

  列名,表的列名称。

  常量, 任意的数字,字符串等等。

  表达式,任意的表达式,例如case,字符串的拼接。

  函数,自定义函数和系统函数,通常是系统函数,例如now()

  特殊符号,例如*

  关键字,  as 别名,distinct 去重。

    1.2  from

  from部分,有以下两种类型。

  table:表名称

  Table link:多表之间的join。

  table又有四种子类型。

  Permanent tables普通的,持久化的表。

  Derived tables派生表,临时存储在缓存中的结果集,例如子查询语句的结果集

  Temporary tables临时表,通过create temporary table语句创建的表,在某个时间点,数据会被清空,例如session过期。

  virtual tables虚拟表,例如视图, view。

 1.3  where

  A where clause may contain one or more conditions, separated by the operators and and or. If multiple conditions are separated only by the and operator, then all the conditions must evaluate to true for the row to be included in the result set.

  Where是由1到N个condition,通过and和or连接起来的。结果集中的任意一条数据满足where中的所有条件。

  A condition is made up of one or more expressions combined with one or more operators.

  条件由1到N个表达式,通过操作符组合而成。例如 age > 23,操作符为大于符号,两边为表达式,列名。

  条件有以下五种类型

  等值条件:例如等于,不等于。

  范围条件:大于,小于,大于等于,小于等于,between。

  成员条件: in, 多个等值条件用or连接,例如 (name =’a’ or name=’b’)。

  匹配条件:like(), 正则表达式等。占位符:_(下划线):代表任意一个字符。%:代表0到N个任意字符。

  null条件: xx is null 或 xx is not null

 1.4  group by

  When grouping data, you may need to filter out undesired data from your result set based on groups of data rather than based on the raw data. Since the group by clause runs after the where clause has been evaluated, you cannot add filter conditions to your where clause for this purpose.

  基于结果集进行分组。注意事项如下:

  1. group by是基于结果集的二次处理,运行在where之后。
  2. select 中必须存在分组的字段,例如group by name,那么name必须出现在select语句中。
  3. 即使不使用group by语句,也会分组,当使用聚合函数时,会将整个表视为一组,例如select max(salary) from table_name,虽然没有group by语句,但也进行了分组。

 1.5  having

  having与where基本相同,分组过程中会自动去除null值,不需要null值条件。

  在使用having时,需遵循只将分组字段或聚合函数作为条件,原因如下:

  having语句作用是在分组过程中排除不想要的数据。若不使用分组字段作为条件,完全可以放入where条件之后。

  类似于数据流水线,第一道手续是where,第二道手续才是having。若前面手续已经过滤掉不想要的数据,那么后续的数据处理量会减少。

 1.6  order by

  order by 组成结构: order by expression (desc || asc)

  expression有三种类型,任意的字段,基于字段的函数,数字(1表示查询的第一个字段,以此类推)。

 1.7  limit

  limit N, 从第一条开始,返回前N条数据,若N是负值,从末尾开始,返回最后N条数据。

2、执行步骤

  第一步,首先校验权限,是否有执行语句的权限,是否有数据的权限。

  第二步,查询优化器优化当前的查询语句。

  第三步,执行查询。

  第四步,返回结果集,若没有结果,则返回empty set。

  查询根据上述七个组成部分,可以分为五道手续。

  第一道,select from where,返回初始结果集。

  第二道,group by having,对结果集进行分组。

  第三道,order by,对结果集进行排序

  第四道,limit,返回前N条。

  第五道,Union等诸如此类,会将单个结果集拼接为最终结果集。

posted @ 2023-10-22 17:00  蜗牛旅行1899  阅读(15)  评论(0编辑  收藏  举报