一、連接數據庫 mysql -u user -p 退出連接 QUIT
二、查看數據庫,創建數據庫,使用數據庫查看數據庫 show databases;
顯示當前使用的數據庫中所有表 SHOW TABLES;
mysql表操作
1、查看表
show tables; # 查看數據庫全部表
select * from 表名; # 查看表所有內容
2、創建表
create table 表名(
列名 類型 是否可以為空,
列名 類型 是否可以為空
)ENGINE=InnoDB DEFAULT CHARSET=utf8
3、刪除表
drop table 表名
4、清空表內容
delete from 表名
truncate table 表名
5、修改表
復制代碼
添加列: alter table 表名 add 列名 類型
刪除列: alter table 表名 drop column 列名
修改列:
alter table 表名 modify column 列名 類型; -- 類型
alter table 表名 change 原列名 新列名 類型; -- 列名,類型
添加主鍵:
alter table 表名 add primary key(列名);
刪除主鍵:
alter table 表名 drop primary key;
alter table 表名 modify 列名 int, drop primary key;
添加外鍵: alter table 從表 add constraint 外鍵名稱(形如:FK_從表_主表) foreign key 從表(外鍵字段) references 主表(主鍵字段);
刪除外鍵: alter table 表名 drop foreign key 外鍵名稱
修改默認值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
刪除默認值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
6、基本數據類型
MySQL的數據類型大致分為:數值、時間和字符串
mysql表內容操作
1、增
insert into 表 (列名,列名...) values (值,值,...)
insert into 表 (列名,列名...) values (值,值,...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from 表
例:
insert into tab1(name,email) values('zhangyanlin','zhangyanlin8851@163.com')
2、刪
delete from 表 # 刪除表里全部數據
delete from 表 where id=1 and name='zhangyanlin' # 刪除ID =1 和name='zhangyanlin' 那一行數據
3、改
update 表 set name = 'zhangyanlin' where id>1
4、查
select * from 表
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1
a、條件判斷where
select * from 表 where id > 1 and name != 'aylin' and num = 12;
select * from 表 where id between 5 and 16;
select * from 表 where id in (11,22,33)
select * from 表 where id not in (11,22,33)
select * from 表 where id in (select nid from 表)
b、通配符like
select * from 表 where name like 'zhang%' # zhang開頭的所有(多個字符串)
select * from 表 where name like 'zhang_' # zhang開頭的所有(一個字符)
c、限制limit
select * from 表 limit 5; - 前5行
select * from 表 limit 4,5; - 從第4行開始的5行
select * from 表 limit 5 offset 4 - 從第4行開始的5行
d、排序asc,desc
select * from 表 order by 列 asc - 根據 “列” 從小到大排列
select * from 表 order by 列 desc - 根據 “列” 從大到小排列
select * from 表 order by 列1 desc,列2 asc - 根據 “列1” 從大到小排列,如果相同則按列2從小到大排序
e、分組group by
select num from 表 group by num
select num,nid from 表 group by num,nid
select num,nid from 表 where nid > 10 group by num,nid order nid desc
select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
select num from 表 group by num having max(id) > 10
特別的:group by 必須在where之后,order by之前
浙公網安備 33010602011771號