limit
mysql> SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15
//为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:
mysql> SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.
//如果只给定一个参数,它表示返回最大的记录行数目:
mysql> SELECT * FROM table LIMIT 5; //检索前 5 个记录行
//换句话说,LIMIT n 等价于 LIMIT 0,n。
order by
//排列 asc升,desc降
select * from student s order by s.grade asc ,sno desc
/该例子先按成绩排,成绩相同按学号排
命令行
show databases; //展示数据库
user 库名;//进入数据库
show tables;
select database(); //显示当前库名
select version(); //数据库版本
desc 表名; //显示表列属性
别名
select sno as no from student;
select sno no from student;
select sno as "a no" from student;
去重DISTINCT
select DISTINCT course_id from table;
+号
若数字则相加,字符则尝试转换为数字,失败则变为0,有null的话计算结果为null
delimiter
delimiter $$ //表示以后用 $$ 结束语句,一般用于创建函数
select * from table $$ //(;$$)也可以
模糊查询
like // %多个字符 //单个字符 //转义符:\ 或 like('$_三') ESCAPE '$'
between and
in //where sname in ('zs',ls');
is null | is not null //where sno is null || is not null
EXISTS && IN
SELECT * from student s1 where EXISTS (SELECT * from studentmvc s2 WHERE s2.sno = s1.stuNo)
SELECT * from student s1 WHERE s1.stuNo in (SELECT sno FROM studentmvc s2 WHERE s2.sno = s1.stuNo)
/*
此二者结果一模一样
exists返回的是boolean类型,即验证该条件成不成立,所以select啥都可以,重要的是where之后的条件
内表小用in,内表大用exists
*/
常见函数 :select 函数名(参数)
1. 单行函数
concat('a','b') //ab
length('张s') // 4:字节个数,utf-8下汉字3个,GBK下2个
ifNull(列名字,0) //null则为0
upper('Zs') // ZS
lower('Zs') // zs
substr('一二三四五六七八',7) //开始位置 七八九
substr('一二三四五六七八',2,3) //其实索引,长度 二三四
instr('一二三四五六七八','三四五') //字符串第一次出现位置 : 3
trim() //去前后空格
trim('a','abcadea') //去前后a bcade
lpad('一二三',10,'*') //左填充:*******一二三(7+3)
rpad('一二三',10,'*') //右填充:一二三*******(3+7)
replace('ABCABCABC','A','X') // 替换:XBCXBCXBC
2. 分组函数(做统计)
round(1.65) //四舍五入:2
round(1.65,1) //四舍五入,保留位数:1.7
ceil(1.01) //向上取整:2 (返回>=的最小)
floor(1.99) //向下取整 1 (返回<=的最小)
truncate(1.9999999,1) //截断,保留1位:1.9
mod(10,-3) //取余: 1 公式:a-a/b*b
FLOOR(i + RAND() * (j – i)) //获取i <= v < j的随机数字v
3. 日期函数
now() //日期+时间
CURDATE() //日期
CURTIME()//时间
#年、月、日、小时、分钟、秒
YEAR(now()) //参数时间的年
/*
年 Y-2019 y-19
月 m-02 c-2
日 d-01
小时 H-16 h-4(12小时)
分钟 i-02
秒 s-02
*/
str_to_date('9-13-1999','%m-%d-%Y') //日期格式字符转日期格式:1999-09-13
date_format('2018/6/6','%Y年%m月%d日') //日期格式转字符:2018年6月6日
4.其他函数
version() //mysql版本
DATABASE() //当前数据库
USER() //当前用户
5.流程控制函数
if(10>5,'10>5','10<5')//类似 ? :
case sno
when 1 then '1号'
when 2 then '2号'
else '3号'
6. 聚集函数
count() 技术
min() 最小值
max() 最大值
sum() 总和
avg() 平均值
CAST
CAST函数语法规则是:Cast(字段名 as 转换的类型 ),其中类型可以为:
CHAR[(N)] 字符型
DATE 日期型
DATETIME 日期和时间型
DECIMAL float型
SIGNED int
TIME 时间型