数据库基础知识(2)

一、数据库相关的SQL

每一个工程对应一个数据库,存储数据需要先创建一个数据库,然后在数据库中创建表

查看所有数据库

show databases;

创建数据库

create database 数据库名称;

create database db1;

创建数据库 指定字符集

create database 数据库名称 character set 字符集;

create database db2 character set gbk;

查看指定数据库详情

show create database 数据库名称;

show create database db1;

删除数据库

drop database 数据库名称;

drop database db1;

使用数据库

use 数据库名称;

use db1;

二、表相关的sql(增删查)

表是关系型数据库存储数据的单位,数据库中存储数据需要先创建表,往表中存储数据.执行表相关的sql时一定要先选择数据库

创建表

create table 表名(字段1名 字段1类型, 字段2名 字段2类型,.....);

create table stu(id int,name varchar(10),age int, chinese int, math int,english int);

创建表指定引擎和字符集

create table 表名(字段1名 字段1类型, 字段2名 字段2类型,.....) engine=表引擎 charset=字符集; 

create table t1(id int,name varchar(10)) engine=myisam charset=gbk; 

表引擎:

  1. innodb:支持数据库的高级操作,包括:事务 外键等
  2. myisam:仅支持数据的增删改查操作

查看所有表

show tables; 

查看指定表详情 / 表的字段信息

show create table 表名;  / desc 表名;

删除表

drop table 表名;

truncate table 表名;(删除表并创建一张空表,自增清零)

三、表相关sql(改)

修改表的名称

rename table 原名 to 新名;

rename table person to t_person;

修改表的引擎和字符集

alter table 表名 engine=表引擎charset=字符集;

alter table tperson engine=myisam charset=gbk; 

添加表的字段

-最后面格式: alter table 表名 add 字段名 字段类型; alter table tperson add age int; 

-最前面格式: alter table 表名 add 字段名 字段类型 first; alter table tperson add chinese int first;

-某个字段的后面格式: alter table 表名 add 字段名 字段类型 after 字段名; alter table tperson add math int after id;

删除字段

alter table 表名 drop 字段名;

alter table t_person drop chinese;

修改字段名称和类型

alter table 表名 change 原字段名 新字段名 字段类型 ;

alter table t_person change age myage int;

修改字段的类型和位置

alter table 表名 modify 字段名 字段类型 first/after xxx;

alter table t_person modify myage int after id;

四、数据相关的SQL

插入数据

-全表插入:要求插入的数据的数量和顺序要和表字段的数量顺序一致,

insert into 表名 values(值1,值2,值3....);

insert into tstu values(1,'zhangsan',23);

-指定字段插入

insert into 表名 (字段1,字段2...) values(值1,值2...);

insert into tstu (id,name) values(2,'lisi');

-批量插入

insert into 表名 values(值1,值2,值3....),(值1,值2,值3....),(值1,值2,值3....);

insert into tstu values(3,'悟空',23),(4,'八戒',20),(5,'沙僧',18);

insert into 表名 (字段1,字段2...) values(值1,值2...),(值1,值2...),(值1,值2...);

insert into tstu (id,name) values(6,'刘备'),(7,'关羽'),(8,'貂蝉');

查询数据

select 字段名 from 表名;

select * from tstu;

删除数据

delete from 表名where 条件;

delete from tstu where age is null;

修改数据

update 表名set 数据where 条件;

update tstu set name='卷帘大将',age=200 where id=5;

五、顺序问题

  • 查询语句书写顺序:select – from- where- group by- having- order by -limit
  • 查询语句执行顺序:from - where -group by -having - select - order by -limit

猜你喜欢

转载自blog.csdn.net/a972669015/article/details/86548291