DQL主要指的是SELECT语句。SELECT用于检索从一个或多个表中选择的行,并且可以包括UNION操作和子查询。从MySQL 8.0.31开始,也支持INTERSECT和EXCEPT操作。本章主要对SELECT语句的用法进行逐一的介绍,语法如下:
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr] ...
[into_option]
[FROM table_references
[PARTITION partition_list]]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]]
[HAVING where_condition]
[WINDOW window_name AS (window_spec)
[, window_name AS (window_spec)] ...]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[into_option]
[FOR {UPDATE | SHARE}
[OF tbl_name [, tbl_name] ...]
[NOWAIT | SKIP LOCKED]
| LOCK IN SHARE MODE]
[into_option]
into_option: {
INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name] ...
}
主要包含数字常量和字符串常量:
例如数字相乘或相加:
例如查询数据库版本和当前所在的数据库:
在查询的过程中可以为字段、函数、子查询、表名使用as(也可以不用写)关键字起别名。起别名可以起到如下作用:(1)使用有意义的别名便于理解;(2)对于联合查询如果两个表的字段名相同,可以使用别名进行区分。
查询中用到的关键词主要包含六个,并且他们的顺序依次为
select、from、where、group by、having、order by 、limit
对于我们书写SELECT语句的的顺序如下:
SELECT DISTINCT
select_list
FROM
left_table join_type
JOIN right_table ON join_condition
WHERE
where_condition
GROUP BY
group_by_list
having
having_condition
ORDER BY
order_by_condition
LIMIT limit_number
而MySQL server按照如下的顺序对SELECT语句进行解析:
FROM left_table
ON join_condition
join_type JOIN right_table
WHERE where_condition
GROUP BY group_by_list
HAVING having_condition
SELECT
DISTINCT select_list
ORDER BY order_by_condition
LIMIT limit_number
其中select和from是必须的,关键字的解析如下: