2021-10-26
DML:数据操作语言,主要是操作表中的数据。主要是对数据增、删、改。
插入(insert)
语法:insert into 表名(字段1,字段2,字段3,…) values (值1,值2,值3,…);
- - 向表中字段1,字段2,字段3,…等插入一条数据
DQL
limit:限制,作用是限制查询结果展现条数。
语法:limit x,y
x:从哪里开始输出,第一条是0
y:条数
--查询stu表中前两条数据
select * from stu limit 0,2;
--在stu表中从第二条开始,查询三条数据
select * from stu limit 1,1;
多表联查:
表和表之间的关系:
一对一 | 两张表内的数据,是一行对应一行 |
一对多 | 两张表内的数据,是一行对应多行 |
多对多 | 两张表内的数据,是多行对多行 |
合并结果集(联合查询)
将查询到的数据纵向拼接
/*
1.联合的表的列数,类型要对应
2.union 会去除两个表中重复数据
3.union all 会保留重复数据
*/
select name,birthday from t1
union
select id,name from t2;
select id,name from t1
union all
select id,name from t2;
函数
IF(expr1,expr2,expr3)
如果expr1是TRUE,则IF()的返回值为expr2;否则返回值则为expr3。IF()的返回值为数字值或字符串值,具体情况视其所在语境而定。
--查询学生姓名和成绩,如果没有参加考试,显示“缺考”
select sname,if (score is null,"缺考",score) from stu;
--查询学生姓名和成绩(合格,不合规)
select sname,if(score>=60,"合格","不合格")from stu;
IFNULL(expr1,expr2)
假如expr1不为null,则IFNULL() 的返回值为expe1;否则其返回值为expr2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所用的语境。
case when then else end
case value when [compare-value] then result [when[compare-value] then result…]
[ELSE result] END
select case 3 when 1 then "一" when 2 then “二” else "三" end "结果" from dual;
select
case 3
when 1 then "一"
when 2 then "二"
else "三"
end "结果"
from dual;
--======================
select
case age
when 18 then "18"
else"不是18"
end "结果"
from stu
case when [condition] then result [condition] then result…] [ELSE result] END
/*
case when 条件 then [when 条件 then] [else result] end
==>类似于java的if…else if…else
先判断when后的条件,如果为true,就执行后面的then,其余不再执行
如果为false,执行下一个when后的条件判断,如果为true,就执行then后的语句,其他不再执行
如果为false,执行下一个when…
如果所有的when后都为false,那就执行else后的结果
*/
-- 查询学生学号,姓名,成绩等级(0-59不及格,60-79及格,80-100优秀)
SELECT
sid,
sname,
CASE
WHEN score < 59 THEN
"不及格"
WHEN score < 79 THEN
"及格"
WHEN score <= 100 THEN
"优秀"
END "等级"
FROM
stu;
日期函数
sysdate( ) | 获得当前时间(年月日时分秒) |
addtime(data2,time_interval) | 将time_interval加到date2(时间,是加时分秒) |
current_date( ) | 当前日期(年月日) |
current_time( ) | 当前时间(时分秒) |
current_timestamp( ) | 当前时间戳(年月日时分秒与sysdate()一样) |
date_add(date2,interval d_value d_type) | 在date2中加上日期或时间 |
date_sub(date2,interval d_value d_type) | 在date2上减去一个时间 |
datediff(date1,date2) | 两个日期差 |
now() | 当前时间,与sysdate()一样 |
year|month|day(datetime) | 只返回年|月|日 |
date(datetime) | 返回datetime的日期部分 |
字符——日期互相转换
date_format(date,'%Y-%m-%d') | oracle中的to_char(); | |
str_to_date(date,'%Y-%m-%d') | oracle中的to_date(); | |
%Y | 代表4位的年份 | |
%y | 代表2位的年份 | |
%m | 代表月 | 01~12 |
%c | 代表月 | 1~12 |
%d | 代表月份中的天数 | 00~31 |
%e | 代表月份中的天数 | 0~31 |
%H | 代表小时 | 00~23 |
%k | 代表小时 | 0~23 |
%h | 代表小时 | 01~12 |
%l | 代表小时 | 1~12 |
%i | 代表分钟 | 00~59 |
%r | 代表时间 | 12小时(hh:mm:ss[AP]M) |
%T | 代表时间 | 24小时(hh:mm:ss) |
%S | 代表秒 | 00~59 |
%s | 代表秒 | 00~59 |
日期转字符串:
select date_format(now(),'%Y年%m月%d日 %H:%i:%s') form dual;
字符串转换为日期:
select str_to_date("2010-11-11","%Y-%m-%d")from dual;