在Linux环境下:
进入管理员权限下通过 service mysqld start 启动数据库服务
通过mysql -u root -p 启动数据库,如果没有设置密码,则去掉-p 就可以打开数据库。
查看有哪些数据库,通过 show databases;(分号很重要,一定加) 查看。
选择使用哪个数据库,通过use [数据库名];选定数据库
查看有哪些表,通过show tables;查看。
SQL语句
一、DDL 数据定义语言
1、创建库
create database 【if not exists】 库名;
2、删除库
drop database 【if not exists】 库名;
3、查询库
show database ;
创建表
crate table 表名(
字段名称 字段类型 [字段约束],
...
字段名称 字段类型 [字段约束]
);
字段约束
①主键(非空+唯一)primary key
②外键
③唯一 unique
④非空 not null
⑤默认为空
查看表
1.SHOW CREATE TABLE 表名;
2.DESC tbname;(排列)
修改表(字段名、字段约束、字段类型)
①修改字段类型 change
alter table 表名 change name(原名) newname(修改后的名字)[新的类型];
如:alter table stu change name newname varchar(40) not null;
②修改字段类型 modify
alter table 表名 modify name varchar(20);
③添加字段 add
alter table 表名 add score(字段名) 字段类型;
④删除字段 drop
alter table 表名 drop 字段名 字段类型;
⑤修改表名 rename
alter table 表名 rename 新表名;
删除表
drop table 表名
二、DML 数据操纵语言
1、添加数据 insert load source replace
insert into tbname values(fieldval1,fieldval1..);
insert into stu(id,name,age,sex) values("001","zhangsan",19,"man");
insert into stu(id,name) values("002","lisi");
insert into stu values("003","wangwu",20,"woman"),
("004","zhaoliu",21,"man"),
("005","kaixin",17,"woman"),
("006","gaoxin",16,"woman");
load 大批量插入
replace insert
2、删除数据 delete truncate
delete from tbname [where];
delete from stu where id = "005";
3、修改数据 update
update tbname set Fieldname = newvalue [where];
update stu set sex = "woman";
update stu set age = 18 where id = "002";
4、查询数据 select
1.普通查询
select field1,field2... from tbname [where];
select * from stu;
select id,name,age,sex from stu;
select id,name,age,sex from stu where age > 20;
2.去重查询 distinct
select distinct age from stu;
3.排序 order by asc升序 desc降序
select distinct age from stu
order by age desc;
4.分组 group by
select id,SUM(score)
from result
group by id;
5.多表
例:查询年龄大于等20岁的学生的不及格成绩
1.等值查询
select name,score
from stu,result
where stu.id = result.id and age >= 20 and score < 60;
2.连接查询
1.外连接查询
1.左外连接查询 左表全部存在
select name,score
from (select id,name from stu where age >= 20) a
left join
(select id,score from result where score < 60) b
on a.id = b.id
where score is not null;
2.右外连接查询
select name,score
from (select id,name from stu where age >= 20) a
right join
(select id,score from result where score < 60) b
on a.id = b.id
where name is not null;
3.全外连接查询
select name,score
from (select id,name from stu where age >= 20) a
full join
(select id,score from result where score < 60) b
on a.id = b.id
where name is not null or score is not null;
2.内连接查询
1.内连接查询
select name,score
from (select id,name from stu where age >= 20) a
inner join
(select id,score from result where score < 60) b
on a.id = b.id;
6.联合查询 union || union all
查询所有师生的基本信息(有学生表和老师表两个表)
select tid,name,age,sex from teacher
union all
select id,name,age,sex from stu;
三、DCL 数据控制语言(权限管理)