SQL基础语法—select语句

1 select语句介绍

select语句是值从现存的一个或多个表中查看满足条件的数据,其基本语法如下:

Syntax:
SELECT
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    select_expr [, select_expr ...]
    [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 OUTFILE 'file_name'
        [CHARACTER SET charset_name]
        export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR {UPDATE | SHARE} [OF tbl_name [, tbl_name] ...] [NOWAIT | SKIP LOCKED]
      | LOCK IN SHARE MODE]]

2 select语句关键词介绍

select_expr关键词代表要查询的字段,至少要有一个select_expr,或者如果是查询所有字段,则用*号代替;

table_reference关键词代表查询数据来自的一个或多个表;

where子句代表只查询满足条件的表数据,如果没有 where子句则代表查询表中所有的数据;

where条件中不能使用select-expr中定义的字段别名,因为语句执行顺序是whereselect之前,所以where在执行时字段别名未知;

form table_references子句中指定表名,tbl_name也可以指定别名,当涉及的表不在当前的数据库中,需要使用db_name.tbl_name来指定表和所在的数据库名;

mysql> select t1.name,t2.salary from employee as t1,info as t2 where t1.name=t2.name;
mysql> select t1.name,t2.salary from employee t1,info t2 where t1.name=t2.name;

当多个表中有相同的字段名,且需要查询出来时,需要在select_expr中能够使用tbl_name.column_name来 显式指定要查询哪个表的字段;

group by子句代表分组,通常聚合函数配合使用,如max, min, avg, count, sum

mysql> select sum(score) from scores;
mysql> select sid,count(*),max(score),min(score),avg(score),sum(score) from scores group by sid;

having子句一般是跟在group by子句之后,代表限制分组之后的结果;

mysql> select user,max(salary) from users group by user having max(salary)>10;

order by子句表示查询结果按照顺序排列,默认是升序排列,可以指定desc表名按照降序排列;

limit子句用来限制查询结果的条数,其后可以带两位大于0的正数,第一位代表offset,第二位代表取多少行,一般情况下,limitorder by子句配合使用;

select * from tbl order by id limit 5;
select * from tbl order by id limit 5,10;	## 返回rows 6-15

select...into语句代表将查询结果写入文件中或者定义的参数变量中;

for update关键词代表将查询的数据行加上写锁,直到本事物提交为止;

lock in share mode关键词代表将查询的数据行加上读锁,则其他的链接可以读相同的数据但无法修改加锁的数据;

all/distinct关键词代表是否将查询结果中完全重复的行都查询出来,all是默认值代表都查询出来,指定distinct代表重复行只显示一次;

high_priority代表赋予读操作较高的操作优先级;

max_statement_time=N子句代表设置语句执行超时时间(毫秒);

straight_join关键词代表强制优化器在表连接操作时按照语句中from子句中的表的顺序执行;

sql_big_result/sql_small_result通常是和group by/distinct一起使用,其作用是事先告诉优化器查询结果是大还是小米,以便优化器事先准备好将查询结果存放在磁盘临时表或者快速临时表中以便后续操作;

sql_buffer_result强制将查询结果存入临时表中;

sql_calc_found_rows关键词代表要求查询结果的同时计算结果的行数,以便后续通过select found_rows()直接获取行数;

sql_cache/sql_no_cache代表是否直接从query cache中获取查询结果。

mysql> select count(*),count(all sid),count(distinct sid) from scores;
+----------+----------------+---------------------+
| count(*) | count(all sid) | count(distinct sid) |
+----------+----------------+---------------------+
| 		5 | 			5 | 				2 |

3 select...into语句

select...into语句代表将查询结果存入定义的变量或文件中。

  • select...into var_list将查询结果存入定义的变量;
  • select...into outfile将查询结果按照一定的格式写入到文件中;
  • select...into dumpfile将查询结果以一行的格式写入到文件中且只能写入一行。

select...into使用注意事项

  • 当使用存入变量方法时,需要保证查询结果返回一行,如果不返回数据则报no data错误,如果返回多行则报result consisted of more than one row错误,当返回行数不确定是,可以用limit 1强制只返回一行;
  • 使用select..into outfile 'file_name'时,文件会创建在本地服务器上,所以要确保用户能创建文件,而且此file_name不能已经存在在服务器上以免覆盖其他文件。
SELECT sid,sname,sex INTO OUTFILE '/tmp/students.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM students;
## ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
## My.ini配置文件中添加secure_file_priv=/tmp/后重启再执行,成功

mysql> select * into dumpfile '/tmp/students3.txt' from students;
mysql> select * into dumpfile '/tmp/students4.txt' from students limit 1;
Query OK, 1 row affected (0.00 sec)

4 select语句中的表连接

select语句中涉及到多表查询结果时,就会用到表连接操作。

mysql> help join
table_factor:
    tbl_name [PARTITION (partition_names)]
        [[AS] alias] [index_hint_list]
  | table_subquery [AS] alias [(col_list)]
  | ( table_references )

join_table:
    table_reference [INNER | CROSS] JOIN table_factor [join_condition]
  | table_reference STRAIGHT_JOIN table_factor
  | table_reference STRAIGHT_JOIN table_factor ON conditional_expr
  | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference join_condition
  | table_reference NATURAL [INNER | {LEFT|RIGHT} [OUTER]] JOIN table_factor

join_condition:
    ON conditional_expr
  | USING (column_list)

在MySQL中,join/inner join/cross join三者的作用是一样的;

join语句中表别名的用法:

SELECT t1.name, t2.salary
FROM employee AS t1 INNER JOIN info AS t2 ON t1.name = t2.name;
SELECT t1.name, t2.salary
FROM employee t1 INNER JOIN info t2 ON t1.name = t2.name;

from子句后面还可以跟子查询,但子查询必须带别名:

SELECT * FROM (SELECT 1, 2, 3) AS t1;

inner join或者表之间用逗号隔开,且没有表之间的关联字段,则代表结果是两者的笛卡尔积;

conditional_expr子句一般代表指定两个表之间的关联条件,而where条件中指定查询结果的筛选条件;

straight_joinjoin的用法大致相同,唯一不同是确保左表是先被读取的,以保证优化器的读取顺序。

select语句中的表连接示例:

SELECT * FROM students, scores; ##没有关联条件,表示笛卡尔积
SELECT * FROM students INNER JOIN scores ON students.sid=scores.sid;
SELECT * FROM students LEFT JOIN scores ON students.sid=scores.sid;
SELECT * FROM students LEFT JOIN scores USING (sid);
SELECT * FROM students LEFT JOIN students2 ON students.sid=students2.sid
LEFT JOIN scores ON students2.sid=scores.sid;

5 select语句中的union

union用来将多个select语句的执行结果合并成一个结果。

mysql> help union
Syntax:
SELECT ...
UNION [ALL | DISTINCT] SELECT ...
[UNION [ALL | DISTINCT] SELECT ...]

  • 第一个select语句的column_name会被当做最后查询结果的列名,接下来的每个select语句所一一对应的列应该和第一个语句的列的数据类型最好保持一致

  • 默认情况下union语句会把最终结果中的重复行去掉,这和增加distinct这个关键词的作用一样,如果使用union all则代表最终结果中的重复行保留

select...union使用示例:

mysql> select sid,sname from students
union
select sid,gender from students2;
+-----+-------+
| sid | sname |
+-----+-------+
| 3 | a |
| 4 | a |
| 5 | a |
| 1 | abc |
| 2 | abc |
| 1 | -2 |
| 2 | -1 |


如果对union语句的最后结果做排序或者limit限制,则需要将每个select语句用括号括起来,把order bylimit语句放在最后:

(Select sid,sname from students)
Union
(Select sid,sname from students2)
order by sid limit 2;
+------+-------+
| sid | sname |
+------+-------+
| 1 | aaa |
| 2 | ccc |
+------+-------+
2 rows in set (0.00 sec)
posted @ 2020-03-01 13:47  Dabric  阅读(2480)  评论(0编辑  收藏  举报
TOP