1、在cmd中進入數(shù)據(jù)庫
mysql -u用戶名 -p數(shù)據(jù)庫密碼
2、創(chuàng)建數(shù)據(jù)庫
create database 數(shù)據(jù)庫名稱;
3、查看數(shù)據(jù)庫
show databases;
4、使用數(shù)據(jù)庫
use 數(shù)據(jù)庫名稱
5、刪除數(shù)據(jù)庫
drop database 數(shù)據(jù)庫名稱
6、創(chuàng)建表
create table student(
-> id int(3) auto_increment not null primary key,
-> name char(10) not null,
-> address varchar(50) not null,
-> year date
-> );
7、表插入數(shù)據(jù)
insert into student values(1,'小明','中國廣州',20221111);
8、修改表名:
rename table 舊表名 to 新表名;
9、查詢當前表結(jié)構(gòu)
desc 表名稱
10、查看表詳細結(jié)構(gòu)的命令:
show create table 表名稱;
或
show full columns from 表名稱;
11、查詢一個表里面所有的數(shù)據(jù)
select * from 表名
12、查看具體的一條數(shù)據(jù)
select * from 表名稱 where name='小明';
13、修改表的字段類型
alter table 表名 modify column id tinyint;
或alter table 表名 modify id tinyint;
14、增加表的字段
alter table 表名 add grade int not null;
15、刪除表的字段
alter table 表名 drop sex;
16、修改字段名稱
alter table student change grade sex char(10);
17、修改字段的排列順序
alter table 表名 modify name char(10) first;
注意:change/first | after 字段名 這些關(guān)鍵字都是屬于MySQL在標準上SQL上的擴展,在其他的數(shù)據(jù)庫上不一定適用
18、更新一條數(shù)據(jù)
update student set address='中國惠州' where id=4;
19、刪除單表中的數(shù)據(jù)
delete from student where id=3;
20、排序(由高到低)
select * from student order by id desc;
21、排序(由低到高)
select * from student order by id asc;
22、聚合
(1)sum求和
select salary sum(字段名) from 表名
(2)count記錄總數(shù)
select count(*) from 表名
(3)max最大值
select max(字段名) from 表名
(4)min最小值
select min(字段名) from 表名
(5)group by分類聚合
select department,sum(salary) from teacher group by department;
(6)with rollup分類聚合后的結(jié)果進行再匯總
select department,sum(salary) from teacher group by department with rollup;
(7)having
注意:having和where的區(qū)別在于,having是對聚合后的結(jié)果進行條件過濾,而where是在聚合前就對記錄進行過濾,應(yīng)該盡可能的對記錄進行先過濾!
23、表連接
(1)內(nèi)連接:選取兩張表中相互匹配的記錄
select * from teacher,teacher_record where teacher.id=teacher_record.id;
(2)外連接:不僅僅選舉兩張相互匹配的記錄,并且回選出其他不匹配的記錄
a. 左連接:
概念:包含左邊表中的所有記錄(包括右表中沒有和它匹配的記錄)
select * from teacher left join teacher_record on teacher.id=teacher_record.id;
b. 右連接:
概念:包含右邊表中的所有記錄(包括左表中沒有和它匹配的記錄)
select * from teacher right join teacher_record on teacher.id=teacher_record.id;
左連接和右連接是可以相互轉(zhuǎn)換的!
24、子查詢
需求:一個查詢需要另一個查詢的結(jié)果參與的時候
用于子查詢的關(guān)鍵字:
in語法:select * from teacher where id in (select id from teacher_record);
注意點:in后面的子語句必須只返回一個字段
若查詢結(jié)果唯一(只有一條)可以使用=代替in
not in 與上面那個相反
25、額外添加主鍵
alter table student_record add primary key(id);
26、添加自動增加字段
alter table student_record modify id int auto_increment;
27、刪除主鍵(前提是如果有auto_increment要先刪除auto_increment才行)
alter table student_record drop primary key;
28、刪除auto_increment
alter table student_record modify id int
29、查看當前數(shù)據(jù)庫的字符集和校對規(guī)則
show variables like 'character_set_database';
show variables like 'collation_database';
30、創(chuàng)建數(shù)據(jù)庫的同時設(shè)置字符
create database student default character set utf8