1.檢驗是否安裝成功
命令臺 services.msc 找到mysql服務
cmd path 是否有 mysql的bin目錄
2.啟動和停止mysql服務
net stop mysql
net start mysql
3.登陸mysql
mysql -u root -p caocao
4.其它命令
\h,?,\q exit, quit status use
5.創建數據庫
create database db_name;
6.查看數據庫
show databases;
show create database db_name;
7.刪除數據庫
drop database db_name;
8.選擇數據庫
use db_name;
查看當前使用的數據庫
select database();
9.創建表
create table table_name
( field1 datatype,
field1 datatype,
field1 datatype
)
10.查看表
show tables;
查看表結構
desc table_name;
查看建表語句
show create table table_name;
11.修改數據表
增加列
alter table table_name add colum datatype;
修改列
alter table table_name modify colum datatype;
刪除列
alter table table_name drop colum;
修改表名
rename table table_name to new_table_name;
修改列名
alter table table_name change colum_name new_colum_name datatype;
12.刪除表
Drop table table_name;
13.約束條件 說明
primary key 主鍵約束,用于唯一標識對應的記錄
foreign key 外鍵約束
not null 非空約束
unique 唯一性約束
default 默認值約束,用于設置字段的默認值
13.1 主鍵約束
每個數據庫最多只能有一個主鍵約束,不能重復,不能為空,
字段名 數據類型 primary key;
13.2 非空約束
字段名 數據類型 not null;(可以有多個)
13.3 唯一約束
字段名 數據類型 unique;
13.4 默認約束
字段名 數據類型 default 默認值;
13.5設置表的字段值自動增加
auto_increment
字段名 數據類型 auto_increment;
14.為表中所有字段添加數據
insert into table_name
values(value1,value2...)
為表指定字段添加數據
insert into table_name (colum1, colum2...)
values(value1, value2...)
同時添加多條記錄
insert into employee
values(value1, value2..),
(value1, value2..),
(value1, value2..);
15.更新數據
update table_name
set col_name=expr1,...
[where where_definition]
16.刪除數據
delete from table_name
[where where_definition];
truncate table_name;(與不帶where的delete相同,但是他的速度更快)
drop table(刪除表本身)
17.單表查詢
select [distinct] * {colum1, colum2...} from rable_name;
查詢所有字段
select * from table_name;
查詢指定字段
select colum1,colum2...from table_name;
18.按條件查詢
帶關系運算符的查詢
select * from table_name where expr;
between .. and
in(set)
like ‘x%’;
is null
and or not
19.高級查詢
聚合函數
count() 返回某行的列數
sum() 返回某列值得和
AVG() 返回某列的平均值
MAX()
MIN()
- limit限制查詢結果的數量
select colum1 ,colum2,...
from 表名
limit [offset]記錄數
21.為表和字段取別名
為表取別名
select 表別名.id, 表別名.name ... from 表名 as 表別名
where 表別名.id = 2...
為字段取別名
select 字段名 [as] 別名 [字段名 [as] 別名,...] from 表名;
22.多表操作
為表添加外鍵約束
CREATE TABLE department(
id INT PRIMARY KEY auto_increment,
name VARCHAR(20) NOT NULL
);
CREATE TABLE employee(
id INT PRIMARY KEY auto_increment,
name VARCHAR(20) NOT NULL,
dept_id INT,
FOREIGN KEY (id) REFERENCES department(id)
);
表已存在,通過修改表的語句增加外鍵
alter table 表名 add constraint 外鍵名 foreign key(外鍵字段名)
references 外表表名(主鍵字段名);
刪除外鍵約束
alter table 表名 drop foreign key 外鍵名;