MySQL基础知识

MySQL登录

-u表示后面跟连接数据库的用户名,-p表示需要输入密码

mysql -uroot -p

查看以及创建数据库

show databases;
create database xxx;

查看数据库表

use xxx
show tables;

创建数据库表

create table tablename(
	column_name_1 column_type_1 constraints,
	column_name_2 column_type_2 constraints,
	...
	column_name_3 column_type_3 constraints
	)

查看表的定义结构  

description 表名(desc 表名)

输出全面的表信息

show create table 表名 G;

删除表

drop table 表名

修改表中字段的限制条件

alter table 表名 modify 字段名 限制条件;

增加表字段

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';
原文地址:https://www.cnblogs.com/luxiaojun/p/10076472.html