mysql单表查询总结,包括基础语法、数据过滤、去重、排序等
-- 基本查询套路
select 字段1,字段2,函数(字段...)...
from 表
where 字段 = ... and|or 字段 <> ..
order by 字段
-- 查询customers表的所有字段
-- * 代表一张表的所有字段
select *
from customers;
-- 查询customers表的所有字段
-- select 后面把表的所有字段罗列出来
select
cust_id
,cust_name
,cust_address
,cust_city
,cust_state
,cust_zip
,cust_country
,cust_contact
,cust_email
from customers
;
-- 查询customers表id和name
select
cust_id
,cust_name
from customers
;
-- 给字段重新命名
-- 将customers 的 cust_name 更改为customer_name
-- as 可以给表或者字段指定别名,其中as 可以省略
select cust_name as customer_name
from customers
;
-- 给表指定别名,如customers 指定别名为cust
select *
from customers as cust
;
-- 过滤查询结果
-- 检索cust_name 以C开头的customers
-- 模糊匹配使用like 关键字,其中 % 代表任意多个字符,_代表单个字符
select *
from customers
where cust_name like 'C%'
;
-- 检索名字以C开头,或者来自Chicago 这个城市的customer
select *
from customers
where cust_name like 'C%'
or cust_city = 'Chicago'
;
-- 逻辑关键词:or and not
-- 判断运算符: = <>
-- 查询不属于Chicago 这个城市的customer
select *
from customers
where cust_city <> 'Chicago'
;
-- 或者
select *
from customers
where not(cust_city = 'Chicago')
;
-- 在查询过程中,可以使用 or and not 组合查询条件,但是他们的组合后,有执行的优先级
-- 我们不需要特意的记住有限级的顺序,推荐使用 () 指定优先级顺序
-- 查询来自Chicago并且名字以C开头 或者 有email 地址的顾客
select *
from customers
where (cust_name like 'C%' and cust_city = 'Chicago')
or cust_email is not null
;
-- 扩展 数据库中的null
-- null 和 空字符串 '' 是有区别的,null 表示什么都没有,而空字符串是有值的
-- 判断字段是否为null,因该用 字段 is null/ 字段 is not null 进行判断
-- null 和 任何数字的 + - * / 的数据运算得到的都是 null
-- null 和 任何值的比较 返回值都是 null
select 1 + null ;
select 1 * null;
select 1 = null;
select null = null;
-- 使用 in 进行范围查询
-- in列表不能使用通配符(模糊查询)
select *
from customers
where cust_city in ('Chicago','Columbus')
;
-- 使用between and 对数字范围查询
select *
from products
where prod_price between 10 and 15
;
-- 函数,是对输入的数据经过一些列的转换映射为另外的值
-- 数学函数
select 1 + 1 as res;
select 10%3 as res;
select mod(10,3) as res;
select sin(60) as res;
select round(10.2222,2) as res;
-- 字符串函数
select concat('a','b') as res;
select concat_ws('_','a','b','c') as res;
select replace('abc','a','') as res;
select instr('abc','b') as res;
select repeat('a',5);
-- 日期函数
select now();
select curdate();
select year(now()) as y;
select month(now()) as y;
select date_add(curdate(),interval 1 day);
select datediff(curdate(),'2022-10-01') as res;
-- 逻辑函数
select if(10 > 5,'big','small') as res;
select case when 10 > 5 then 'big' else 'small' end as res;
-- 去重的方式一边有两种
-- distinct
select distinct order_num
from orderitems
;
-- group by
select order_num
from orderitems
group by order_num
;
-- order by 字段 asc|desc
-- asc 升序,默认选项
-- desc 降序
select *
from products
order by prod_price desc
;
-- 组合排序
select *
from products
order by vend_id,prod_price
;