SQL主要由数据定义、数据操纵、数据控制、使用规定这四个部分组成。
查询基础语句即:Select……from
查询表中所有字段:用*代替字段名
Select *
From employees;
它的不足是:查询结果中字段顺序与原始表中完全一致,不能灵活变动字段顺序
②当要查询的字段存在重名的情况,使用别名可以区分开来
用as关键字
Select name as 姓名;
From employees;
用空格
Select name 姓名;
From employees;
利用Group by关键字
Select Distinct department_id
From employees;
groub by department_id;
利用row_number() over
其中:partition by用来分组,order by用来排序,row_number() over用来去重
Select * from (
select *,Row_number() over(
partition by department_id order by department_id desc) ;
两个操作数都为数值型:加法运算
Select 9+9;
一个字符串一个数值型:试图将字符串转换为数值型,转换成功,则继续加法运算;转换失败,则将字符串转换为0
Select ‘1‘+2; 其结果为3
Select ‘lily’+2; 其结果为2
只要其中一个为null,结果肯定为null
Select null+2; 其结果为null
基本语法:Select 查询列表
From 表名
Where 筛选条件
按条件表达式筛选
Mysql的条件运算符:> < = <> >= <=
Select name
From employee
Where department_id=1700;
按逻辑表达式筛选
Mysql的逻辑运算符:&& and || or ! not
Select name
From employee
Where salary>15000 and salary<17000 ;
模糊查询
Mysql的模糊查询运算符Like Between and in is null is not null
① Like:和通配符搭配使用
通配符:%(代表任意多个字符)和_(代表任意一个字符)
Select salary
From employee
Where name like ‘_a_c%’ ;
当要查询的结果中包含_或%时:使用转义
Select salary
From employee
Where name like ‘a_c%’ (第二个下划线代表查询结果第三个字符为)
② Between and:等价于>=左临界值<=右临界值,可以使语句更简洁
Select name
From employee
Where salary between 15000 and 17000(包含临界值)
③ In:判断某字段的值是否属于in列表中的某一项(in列表中值的类型必须统一,不支持通配符,因为通配符要与like搭配,这里in相当于等号),可以使语句更简洁
Select name
From employee
Where job_id in (‘AD_PRES’, ‘IT_PROG’, ‘FI_ACCOUNT’) ;
④ Is null:等于号不能查询null,因此要用Is(not) null查询
且仅可以判断null
Select name
From employee
Where commission_pct is null ;
⑤ 安全等于<=>:判断是否等于,可用于查询普通等号和null
Select name
From employee
Where commission_pct <=> null ;
基本语句:Order by 排序列表 asc/desc
Asc升序,desc降序,默认升序
Order by子句必须放在select语句中最后一条子句
例:
Select name,salary
From employee
Where commission_pct <=> null
Order by salary;
按表达式排序
Select name, salary * 12*(1+commission_pct)
From employee
Where commission_pct <=> null
Order by salary * 12 *(1+commission_pct);
按别名排序
Select name, salary * 12 *(1+commission_pct)年薪
From employee
Where commission_pct <=> null
Order by 年薪;
按函数排序
Select length(name)长度, name, salary
From employee
Where commission_pct <=> null
Order by length(name);
多列排序
Select length(name)长度, name, salary
From employee
Where commission_pct <=> null
Order by length(name)Desc , salary Asc ;