最近在复习回顾SQL语句,遗忘真的是学习最大的天敌,所以特意整理一些基本的SQL语句,以备使用时参考。所以本文比较简略,适合稍稍有一点SQL基础的人阅读。
推荐两个学习资源给大家,也是我整理这个博客的参考资料,
本文的所有SQL语句都是基于MySQL Tutorial网站给的一个数据库样例classicmodels,这个样例的关系图如下,
show databases; -- 显示所有数据库
use classicmodels; -- 使用classicmodels数据库
show tables; -- 显示当前数据库的所有表
describe customers; -- 显示customers表的详细信息
select * from customers; -- 检索customers表中的所有列
select customerName,phone,city from customers;
select distinct city from customers; -- 检索customers表的city列中所有不同的数据
select customerName from customers limit 5; -- 检索customers表的customerName列的前5条记录
select customerName from customers limit 5 offset 3; -- 检索customers表的customerName列的,从第3条记录往后的5条记录
select customerName from customers order by customerName; -- 按照customerName列排序
select customerName,country from customers order by customerName,country; -- 按照customerName列和country列排序
select productName,buyPrice from products order by buyPrice desc; -- desc关键字表示降序,默认升序
select productName,buyPrice from products order by buyPrice desc,productName;
select productName,buyPrice from products order by buyPrice desc limit 1;
select productName,buyPrice from products where buyPrice>50; -- 过滤规则为buyPrice大于50
select productName,buyPrice from products where buyPrice<>50; -- 过滤规则为buyPrice不等于50
select productName,buyPrice from products where buyPrice between 50 and 55; -- 过滤规则为buyPrice在50和55之间
select productName,buyPrice from products where buyPrice>50 order by buyPrice; -- 过滤并排序
select productName,buyPrice from products where productName='The Titanic';
select productName,buyPrice from products where buyPrice is null;
select productCode,buyPrice from products where buyPrice>50 and productCode='S10_2016'; -- 使用and并列两条过滤规则,即两个条件都满足的记录才会被返回
select productCode,buyPrice from products where buyPrice>50 or productCode='S10_2016'; -- 使用or并列两条过滤规则
select productCode,buyPrice from products where buyPrice>50 and (productCode='S10_2016' or productCode='S10_4698'); -- and的优先级高于or,所以要改变优先级需要加小括号
select productCode,buyPrice from products where productCode in ('S10_2016','S10_4698'); -- prodectCode的值在('S10_2016','S10_4698')中的记录才会被返回
select productCode,buyPrice from products where productCode not in ('S10_2016','S10_4698'); -- 与上一条相反
select productName from products where productName like '%Rom%'; -- 通配符%匹配任意个数个任意字符
select productName from products where productName like '%Rom__%'; -- 通配符_匹配单个任意字符
未完,待续(●'◡'●)