多条SQL语句必须用分号(;)分隔;
SQL语句不区分大小写,但列名和表名是否区分看DBMS配置;
注释:
行内注释 --
整行开头使用整行注释 #
代码注释 /……/
一、SELECT -- 检索数据
从一个或多个表中检索信息
select 列名 from 表名 -- 选择单列输出
select 列1, 列2 from 表名 -- 选择多列输出
select * from 表名 -- 检索所有列
select distinct 列名 from 表名 -- 检索不同值(输出去重)/返回具有唯一性的行,distinct针对后面所有的列
select 列名 from 表名 limit 5 -- 限制结果
select 列名 from 表名 limit 5 offset 5 -- 返回第5行的5行数据
二、ORDER BY -- 排序检索数据
需保证order by 是select语句中最后一局
select 列名 from 表名
order by 列名
select 列1, 列2 from 表名
order by 列1, 列2 -- 按多个列排序,当列1出现相同值才会按列2排序
select 列1, 列2 from 表名
order by 列1 desc, 列2 -- 降序,desc只应用位于前面列名,对列2不指定
三、WHERE子句 -- 过滤数据
= 等于;<> 不等于;!= 不等于;< 小于;<= 小于等于;!<不小于;> 大于;>= 大于等于;!> 不大于;between 在指定的两个值之间;is null 为null值
select product_name, prod_price
from Products
where prod_price = 3.49;
select vend_id, prod_name
from Products
where vend_id <> 'DLL01'; -- 字符串需要加引号,不匹配检查
where prod_price between 5 and 10; -- 5-10之间
空值检查(空值:unknow未知)
-- 空值不代表0,空字符串,空格
where prod_price is null; -- 过滤不包含指定值的所有行时,不含null值
四、WHERE+ not/in -- 高级数据过滤
逻辑操作符(logical operator):联结或改变where子句中的关键字,and & or
() 求值优先级最高,and其次,or再次
where vend_id = 'DLL01' and prod_price <= 4; -- 两者都需满足,且
where vend_id = 'DLL01' or vend_id = 'BRS01'; -- 或
【in】
where (vend_id = 'DLL01' or vend_id = 'BRS01')
and prod_price >= 10;
where vend_id in ('DLL01', 'BRs01');
【not】
where子句中用来否定其后条件的关键字
where not vend_id = 'DLL01'
五、LIKE+通配符 -- 用通配符过滤
通配符(wildcard):用来匹配值的一部分的字符
1、%:任意字符出现任意次数
select prod_id, prod_name
from Products
where prod_name like 'Fish%'; -- 找出所有以词Fish开头的产品
where prod_name like '%bean bag%'; -- 匹配任何位置包含文本bean bag的值
注:① 字符串中空格,比如F%y匹配时,'Fly ',无法匹配,可以使用函数去掉字符串中空格,或者搜索时添加F%y%;② 空值,'%'不匹配空值
2、_ -- 只匹配单个字符
select prod_id, prod_name
from Products
where prod_name like '__ inch teddy bear'; -- inch teddy bear 前面有2个字符才会被匹配
3、[] -- 指定字符集
select cust_contact
from Customers
where cust_contact like '[JM]%'; -- 输出姓名为J或者M打头的客户名字
网友评论