1.and 用法
代表并且的意思,两边同时成立.
select * from student where name='李明' and age='23'
2.or 用法
代表或者的意思,条件中任意一个成立皆可.
SELECT * FROM student WHERE id= '7' AND (code1 = '10' OR code2='11')
3.in 用法
条件任一成立
select * from student where City in('USA','CHAIN')
4.like 用法
模糊查询,%在前匹配 %后边带’李’的数据,两边都有%匹配带’李’的所有数据,%在后,匹配以’李’开头的数据, ._代表一个字符
select * from student where age>20 and name like '%李'
select * from student where age>20 and name like '%李%'
select * from student where age>20 and name like '李%'
select * from student where age>20 and name like '._李%'
5.order by 用法
用于排序,ASC 升序 (默认), 从小到大排序,DESC 降序, 从大到小排序
select * from student where sex='男' ORDER BY id DESC
6.group by 用法
用于分组,一般与聚合函数{count(),sum(),avg(),max(),min() } 一起使用,by后面跟要分组的字段
select sex as 性别,count(sex) as 数量 from student GROUP BY sex
7.Having 用法
分组条件,一般用在group by后面,对数据进行过滤.
having与where的区别:
- having是在分组操作执行后, 对分组后的数据进行过滤.
where是在分组操作执行前, 对分组前的数据进行条件过滤 - having后面可以使用 聚合函数
where后面不可以使用 聚合函数 - 当一条SQL语句中, 既有where 又有 group by \ having时, 先执行 where, 再执行 group by, 最后执行having
SELECT 字段1,字段2… FROM 表名 GROUP BY分组字段 HAVING
select sex,name from student GROUP BY sex having age>20
8.inner join on 用法
内连接 语法:
select * from A inner join B on 条件
select * from category c INNER JOIN product p on c.cid=p.category_id
9.left join 用法
左外连接
select c.name count(category_id) from category c LEFT JOIN products p on c.id=p.category_id GROUP BY cname
10.between and用法
between…and… 显示在某一区间的值,含头含尾
SELECT * FROM product WHERE price BETWEEN 200 AND 1000;
11.as 用法
类似于给字段起别名
select sex as 性别,age as 年龄 from student GROUP BY sex
12.Limit 用法
select * from 表名 limit m,n
其中: m是指记录开始的index,从0开始,表示第一条记录
n是指从第 m+1 条开始,取n条。
select * from tablename limit 2,4 //从第三个开始取,取四个数字(3,4,5,6)
select * from tablename limit 1
13.where 用法
最常用的条件语句
select * from student where age>20
14.not 用法
不等于
SELECT * from student where not s_sex='男'
15.distinct 用法
去除重复数据,单独使用只能放在第一个参数位置,与其他函数一起使用无限制
select DISTINCT s_name from student where s_name='李云'
select name,count(DISTINCT(openid)) from wx_user;
16.case…when…then…else…end
判断语句,类似于java中的if…else
then后边的值跟else后边的值类型应保持一致否则会报错.
CASE
WHEN SCORE = 'A' THEN '优'
WHEN SCORE = 'B' THEN '良'
WHEN SCORE = 'C' THEN '中' ELSE '不及格' END
SELECT
`name`,
(CASE WHEN score < 60 THEN '不及格'
WHEN score >= 60 AND score < 80 THEN '及格'
WHEN score >= 80 THEN '优秀'
ELSE '异常' END) AS 评价
FROM
TABLE
17. unsigned 用法
只有正数没有负数,设置字段的属性为:无符号属性 unsigned
//年龄只能为正数不能为负数.
age tinyint unsigned default 18
18.enum用法
对于从多个选项中选择一个,通常设置字段的类型为,单选 enum
sex enum('男','女','保密') default '男',
19 set用法
对于一次可以多选几个选项时,设置字段的类型为, 复选set类型
hobby set('体育','音乐','阅读','象棋') default '体育'
20 is null 用法
判断是否为空
//查找分类id为空的数据
select * from product where category_id IS NULL
21 比较运算符
<:小于
>:大于
<=:小于等于
>=:大于等于
<>:不等于
22,根据分隔符截取字段
SUBSTRING_INDEX(字段,分隔符,索引)
示例:
SELECT
SUBSTRING_INDEX(class_name,'-',1)
FROM
jw_student_info
WHERE
college_id = "2403"
原始数据:华西公共卫生学院-李双
根据‘-’截取出来第一个字符串:华西公共卫生学院