MySQL登陸mysql
-u表示後面跟鏈接數據庫的用戶名,-p表示須要輸入密碼sql
mysql -uroot -p
查看以及建立數據庫數據庫
show databases; create database xxx;
查看數據庫表ide
use xxx show tables;
建立數據庫表blog
create table tablename( column_name_1 column_type_1 constraints, column_name_2 column_type_2 constraints, ... column_name_3 column_type_3 constraints )
查看錶的定義結構 ip
description 表名(desc 表名)
輸出全面的表信息io
show create table 表名 \G;
刪除表table
drop table 表名
修改表中字段的限制條件class
alter table 表名 modify 字段名 限制條件;
增長表字段test
alert table 表名 add column 字段名 限制條件;
刪除表字段
alter table 表名 drop column 字段名;
字段更名
alter table 表名 change 舊錶名 新表名 限制條件;
注意:change和modify都有修改表的定義,不一樣的是change後面須要寫兩次列名,不方便。可是change的優勢是能夠修改列名稱,modify則不能
改變字段的位置
alter table 表名 add 字段名 限制條件 after 字段名;
alter table 表名 modify 字段名 限制條件 first;
修改表名
alter table 舊錶名 rename 新表名;
插入記錄
insert into 表名(字段1,字段2,...,字段n) values(值1,值2,...,值n);
插入多條記錄
insert into 表名(字段1,字段2,....,字段m) values (值1,值2,...,值n),...,(值1,值2,...,值n),(值1,值2,...,值n);
更新記錄
update 表名 set 字段名 = xxx where 條件 = xxx;
刪除記錄
delete from 表名 where 限制條件;
查詢記錄
select * from 表名 條件;
多個限制條件查詢
select 字段名,count(1) from 表名 group by 字段名 order by count(1) desc ;
以聚合結果爲查詢條件用having
select 字段名 count(1) from 表名 group by 字段名 having count(1) >1;
錶鏈接
內鏈接(僅選出兩張表中互相匹配的記錄)
select x,y from 表1,表2 where 表1.字段 = 表2.字段;
select * from 表1 inner join 表2 on 表1.字段 = 表2.字段;
外鏈接(左鏈接和右鏈接)
左鏈接:包含全部左邊表中的記錄甚至是右邊表中沒有和它匹配的記錄
右鏈接:包含全部右邊表中的記錄甚至是左邊表中沒有和它匹配的記錄
select * from student LEFT JOIN course ON student.course_id = course.id; select * from student RIGHT JOIN course ON student.course_id = course.id;
子查詢(in、not in、=、!=、exists、not exists等)
select * from 表名 where xxx in (select xxx from 表名);
記錄聯合(union和union all 的區別是union至關於把union all 的結果進行了一次distinct,去除重複記錄後的結果)
select * from 表1 union/union all select * from 表2...union/union all select * from 表n;
DCL語句
新建用戶
grant select,insert on test.* to 'abc'@'localhost' identified by 'apwd@center';
取消用戶的insert權限
revoke insert on 數據庫.* from 'abc'@'localhost';