原博主博客地址:https://blog.csdn.net/qq21497936
本文章博客地址:https://blog.csdn.net/qq21497936/article/details/80242112
SQL不完全手册(二):高级语句
SQL系列
https://blog.csdn.net/qq21497936/article/details/80207610
https://blog.csdn.net/qq21497936/article/details/80242112
https://blog.csdn.net/qq21497936/article/details/80262309
高级语句
1.指定查询返回的记录条数:top
SQL语法:
SELECT TOP number|percent column_name(s) FROM table_name
mysql语法
SELECT column_name(s) FROM table_name LIMIT number
oracle语法
SELECT column_name(s) FROM table_name WHERE ROWNUM <= number
2.搜索指定匹配或不匹配条件:(NOT) LIKE
SELECT * FROM tabel_name WHERE colume_name (NOT) LIKE 'N%'
3.搜索指定匹配使用的通配符:% _ [charlist] [^charlist][!charlist]
表3:使用LIKE时可使用的通配符
通配符 |
描述 |
% |
替代一个或多个字符 |
_ |
仅替代一个字符 |
[charlist] |
字符列中的任何单一字符 |
[^charlist] 或者 [!charlist] |
不在字符列中的任何单一字符 |
4.规定多个值:where in
指定列的值包含的in后的括号中的所有数据。
5.介于两值之间:where between and
指定两个值之间的数据范围,这些数据可以是数值、文本或者日期
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2
6.别名:AS(alias)
表名别
SELECT column_name(s) FROM table_name AS alias_name
列别名
SELECT column_name AS alias_name FROM table_name
使用一个表别名
使用列别名(输出的时候,列名改为别名了)
7.多表查询:table1*table2…
常用的方法
8.内连接:inner join,left join, right join,full join
inner join:如果表中有至少一个匹配,则返回行;(与join相同)
left join:即时右表中没有匹配的行,也从左表返回所有的行;
right join:即时左表中没有匹配的行,也从右表返回所有行;
full join:只要其中一个表中存在匹配,就返回行;
select * from student join teacher on student.num = teacher.num select * from student inner join teacher on student.num = teacher.num select * from student left join teacher on student.num = teacher.num select * from student right join teacher on student.num = teacher.num select * from student full join teacher on student.num = teacher.num
9.合并两个或多个select语句的结果集:sql union,sql union all
sql union语法(相当于对结果进行distinct了,相同列值只出现一次)
SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2
sql union all语法(相当于对结果未进行distinct了,每列值都出现)
SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2
10.从表中查询结果集,将结果集插入另一个表:sql selectinto
select into语句常用语创建表的备份复件或者用于对记录进行存档。
语法:
SELECT * INTO new_table_name [IN externaldatabase] FROM old_tablename
或者只希望把列插入新表
SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_tablename
备份表,备份列,如下图: