1.DML 操作语言介绍
1.1insert update delete select 语法介绍
1.2insert 对每一个列(竖排,字段)插入数据。
insert 关键字 into 关键字 ti 表名称 values(值 );
insert into table (sid,name,add…..) values (1,李先生….)
插入数据之前要先看表得机构 desc 表名称;
mysql> insert into student(sid,sname,scardid,saddr,shobby,smoney,sdate)
-> values(1001,’zs’,’1234567’,’北京市’,’足球,排球’,10000.11,now()); ## now()是内置函数获取当前时间
mysql> insert ignore into t2 set id=4,name=’ss’ ; ##
mysql> insert into t1 select * from t2; ##
2.update语法介绍
update TABLE_NAME SET xxx=xxx where
注意点: 更新列的个数,where条件,索引 ##有索引得列才可以当作条件语句
show variables like ‘%update%’; ##查看安全更新是否开启
set global sql_safe updates=1; ##开启安全更新之后重新接连数据库
2.1删除表的某个列
delete from t1 where sid=1; ##删除t1表中 sid等于1得列。
drop table ## 直接删除表包括定义 truncate table ## 清空表空间 delete from table #逐行删除
面试有什么区别以及执行得速度:
性能排名 1 2 3
delete from 最慢他是逐行删除。
drop table 要删除表定义 元数据清空,删除ibd文件(操作系统rm )会释放操作系统得 iond得表空间
truncate 保留表定义,清空表空间
2.2 伪删除,状态列得使用(is_delete)
使用update 替代delete
2.3添加状态列 并且设定默认值
alter table t1 add column is_deleted tinyint not null defaulf 0 comment ‘0是未删除1是删除’;
3.select 语句使用得情况(不配合其他子句)
select @@port ## @@是查询系统变量
select @@basedir ,select @@datadir; ## 查看数据存放目录。
select @@innodb_flush_log_at_trx_commit;
show variables like ‘系统参数名称’;
3.1 多子句的执行顺序 以及语法
select
from 从哪来
where 过滤条件
group by 分组条件
select_list 列条件
having 后过滤条件
order by 排序条件
limit 分页
SELECT FROM city;
3.1.1select 配合 使用方法
select from tables; ##查看tables表中得所有数据,生产中谨慎使用尤其是对大表
select name,sid,age from t1 ##查询t1表中得 name,age,sid列数据。
3.1.2 where子句得使用
where = > < >= <= != is not null and between in
SELECT from city WHERE CountryCode=’chn’
select from city where Population < 100
select FROM city WHERE Population BETWEEN 1000000 and 2000000 # 大于100w小于200w
select from city WHERE CountryCode in (‘chn’,’usa’) ## 查询中国和美国得城市
select from city WHERE CountryCode not in (‘chn’,’usa’) ##不显示中国和美国
#select from city where CountryCode=’chn’ and District=’guangdong’ ## 查询中国得广东省
SELECT FROM city WHERE CountryCode=’chn’ or CountryCode = ‘usa’ ##查询中国或者美国
like 模糊查询 like ‘%ch%’最好针对字符串列使用,数字列性能不是很好
select from city where CountryCode like ‘ch%’ ## 已ch开头得 可以前后都是模糊得查找中间得但是前面带百分号不走索引,后面是可以得
3.1.3group by分组函数使用示例:
select CountryCode,count() from city group BY CountryCode ## 统计每个国家城市个数
select CountryCode,sum(Population) from city WHERE CountryCode=’chn’ GROUP BY CountryCode ##统计中国总人口数
sql_mode=only_full_group 要求select_list中的列要么在group by中,要么在聚合函数中。这是一个规则一下是示例
select CountryCode,sum(Population),GROUP_CONCAT(name) from city GROUP BY CountryCode ##group_concat (优化显示信息 一列 变成一行)
3.1.4 having 使用类似于 where 需要在group by 聚合函数后过滤
select CountryCode,count() from city GROUP BY CountryCode HAVING COUNT()>100 ##
wher条件必须在group前面执行,having在group后面执行,having不走索引。
上面是查看 有那些国家有100个城市,查询有100个城市以上的大国
3.1.5order by 排序
prder by 排序语法示例
SELECT CountryCode,count() FROM city GROUP BY CountryCode HAVING count()>100 order by count(*) DESC
SELECT * FROM city ORDER BY Population desc LIMIT 1,10 ##
LIMIT 是显示 1,10行,LIMIT一般搭配ORDER BY 一起使用
LIMIT 3 offset 5 跳过前5行显示3行 显示 6-8
