SQL(i/ˈsiːkwəl/; Structured Query Language)是一套语法标准,不区分大小写。MySQL、sql-server和Oracle都是关系型数据库,在一些高级语法上跟标准SQL略有出入。
Linux用户安装MySQL服务端
yum install mysql-server
安装MySQL客户端
yum install mysql
启动MySQL服务端
service mysqld start
以管理员登录
mysql -h localhost -P 3306 -u root -p'123456' -h:mysql server host,不写时默认是localhost。 -P:mysql server port,不写时默认是3306。 -u:user name,-u后可以加空格也可以不加。 -p:password,密码中可能包含空格,所以要加引号。高版本的mysql不允许在命令行中直接输入密码,此时只输入-p后面不要写密码即可。 创建账号 create user 'tester' identified by '123456'
创建database
create database test
把特定database的操作权限授予一个普通用户
grant all on test.* to tester;
以普通用户登录
mysql -utester -p'123456'
使用database
use test
创建表
#primary key (id) 设置id为主键 #unique key idx_name (name)表示为name创建唯一索引 //索引是什么?从数据库中每次查询数据,都会遍历表。我们创建索引后,就相当于构建一个快速查找树,所以我们要预估那个列会频繁进行where查询,我们对这些列建索引。 create table if not exists student( id int not null auto_increment comment '主键自增id', name char(10) not null comment '姓名', province char(6) not null comment '省', city char(10) not null comment '城市', addr varchar(100) default '' comment '地址', score float not null default 0 comment '考试成绩', enrollment date not null comment '入学时间', primary key (id), unique key idx_name (name), key idx_location (province,city) )default charset=utf8 comment '学员基本信息';
新增记录,必须给not null且无default值的列赋值
insert into student (name,province,city,enrollment) values ('张三','北京','北京','2021-03-05'), ('李四','河南','郑州','2021-04-25'), ('小丽','四川','成都','2021-03-10');
查询
select id,name from student where id>0; select province,avg(score) as avg_score from student where score>0 group by province having avg_score>50 order by avg_score desc;
修改
update student set score=score+10,addr='海淀' where province='北京'; update student set score=case province when '北京' then score+10 when '四川' then score+5 else score+7 end, addr=case province when '北京' then '东城区' when '四川' then '幸福里' else '朝阳区' end where id>0;
删除
delete from student where city= '郑州'; delete from student; --删除表里的所有行 drop table student; --删除表
null