1. 程式人生 > >Linux 中 MySQL常用命令

Linux 中 MySQL常用命令

一、 資料庫登入
mysql -uroot -p
二.、退出資料庫
quit 和 exit或ctrl + d
三、資料庫操作
1. 檢視所有資料庫
show databases;
2. 檢視當前使用的資料庫
select database();
3. 使用資料庫
use 資料庫名;
4. 建立資料庫
create database 資料庫名 charset=utf8;
5. 刪除資料庫
drop database 資料庫名;
6.檢視當前資料庫中所有表
show tables;
7.查看錶結構
desc 表名;
8.建立表結構的語法.
create table 表名(
欄位名稱 資料型別 可選的約束條件);
9.修改表-新增欄位
alter table 表名 add 列名 型別;
alter table students add birthday datetime;
10.修改表-修改欄位-重新命名
alter table 表名 change 原名 新名 型別及約束;
11. 修改表-修改欄位不重新命名
alter table 表名 modify 列名 型別及約束;
12.修改表-刪除欄位
alter table 表名 drop 列名;
13.刪除表
drop table 表名;
14.查看錶的建立語句-詳細過程
show create table 表名;
四、表資料的操作
1.增加
insert into 表名 values (...),
insert into 表名 (列1,...) values(值1,...)
2.刪除
delete from 表名 where 條件
3.修改
update 表名 set 列1=值1,列2=值2... where 條件
4.查詢
select * from 表名;
select 列1,列2,... from 表名;
備註:MySQL的常用型別 bit-int-short-tinyint-x unsigned -decimal char-varchar enum
MySQL常用約束 主鍵 primary key 非空 not null 預設 default 唯一 unique 外來鍵 foreign key
五、其他操作
1.排序:order by
select * from 表名 where 列1 order by 列2 asc|desc;
asc從小到大排列,即升序;desc從大到小排序,即降序
2.分頁:limit
查詢前3行男生資訊:select * from students where gender=1 limit 0,3;
3.最大值:max(列)
查詢女生的編號最大值:select max(id) from students where gender=2;
4總數:count(*)
select count(*) from 表名;
5.最小值:min(列)
查詢未刪除的學生最小編號:select min(id) from students where is_delete=0;
6.求和:sum(列)
查詢男生的總年齡:select sum(age) from students where gender=1;
7.平均值:avg(列)
平均年齡:select sum(age)/count(*) from students where gender=1;
8.分組:group by
根據gender欄位來分組:
select gender from students group by gender;
9.使用內連線查詢班級表與學生表:
select * from students inner join classes on students.cls_id = classes.id;
10.使用左連線查詢班級表與學生表:
select * from students as s left join classes as c on s.cls_id = c.id;
11.使用右連線查詢班級表與學生表:
select * from students as s right join classes as c on s.cls_id = c.id;