csdn| MySQL

MySQL的基本命令

这篇的读书笔记

数据库的基本操作

1.【增】创建/删除数据库

sql 复制代码
create database 数据库名称;
drop database db1;

【查】展示所有的数据库

sql 复制代码
show databases;

使用某个数据库

sql 复制代码
use test;

数据表的基本操作

1.增

sql 复制代码
 create table 表名(
         字段1 字段类型,
         字段2 字段类型,
         ...
         字段n 字段类型
);
例如
 create table student(
 id int,
 name varchar(20),
 gender varchar(10),
 birthday date
 );

2.删

sql 复制代码
drop table stu;

3.改字段alter

sql 复制代码
alter table student rename to stu; //修改表名
alter table stu change name sname varchar(10);  //修改字段名 change
alter table stu modify sname int;    //修改字段类型 modify
alter table stu add address varchar(50);  //添加字段 add

4.查

sql 复制代码
show tables;

这个数据库里有哪些表

sql 复制代码
desc student;

这个表有哪些字段

约束

复制代码
表的约束实际上就是表中字段的限制条件。
  1. 主键约束【唯一且不空】
sql 复制代码
字段名 数据类型 primary key;
  1. 非空约束
sql 复制代码
字段名 数据类型 NOT NULL;

create table student02(
id int
name varchar(20) not null
);
  1. 默认值约束
sql 复制代码
字段名 数据类型 DEFAULT 默认值;

create table student03(
id int,
name varchar(20),
gender varchar(10) default 'male'
);
  1. 唯一性约束
sql 复制代码
字段名 数据类型 UNIQUE;
  1. 外键约束
    建立外键就是想要保证 主表中的主键字段 与 从表中的外键字段 。这两个字段的统一,一个删除,对另一个有影响。具体是什么影响是需要diy的。
sql 复制代码
ALTER TABLE 从表名 ADD CONSTRAINT 外键名 FOREIGN KEY (从表外键字段) REFERENCES 主表 (主键字段);

创建一个学生表 MySQL命令:

create table student05(
id int primary key,
name varchar(20)
);

创建一个班级表 MySQL命令:
create table class(
classid int primary key,
studentid int
);

alter table class add constraint fk_class_studentid foreign key(studentid) references student05(id);

数据表插入数据

这里有一张表

sql 复制代码
 create table student(
 id int,
 name varchar(30),
 age int,
 gender varchar(30)
 );


插入
INSERT INTO 表名(字段名1,字段名2,...) VALUES (值 1,值 2,...);
insert into student (id,name,age,gender) values (1,'bob',16,'male');

更新

sql 复制代码
UPDATE 表名 SET 字段名1=值1[,字段名2 =值2,...] [WHERE 条件表达式];

//将name为tom的记录的age设置为20并将其gender设置为female 
update student set age=20,gender='female' where name='tom';

删除

sql 复制代码
DELETE FROM 表名 [WHERE 条件表达式];

//删除age=14的
delete from student where age=14;  

查询

sql 复制代码
select * from student;
* 是所有的字段
sql 复制代码
select sid,sname from student;
//查询指定字段(sid、sname)

条件查询where

sql 复制代码
select * from student where age>=17;
相关推荐
krielwus2 小时前
Oracle ORA-01653 错误检查以及解决笔记
数据库·oracle
程序员水自流3 小时前
MySQL InnoDB存储引擎关键核心特性详细介绍
java·数据库·mysql
-雷阵雨-3 小时前
MySQL——表的操作
数据库·mysql
阿巴~阿巴~3 小时前
Ubuntu 20.04 安装 Redis
linux·服务器·数据库·redis·ubuntu
想睡hhh4 小时前
mysql表的操作——mysql表的约束
数据库·mysql
shaohaoyongchuang4 小时前
9-mysql编程
数据库
m0”-“0m4 小时前
MySQL、Nignx和Docker在Linux上的安装详解
linux·数据库·mysql
野犬寒鸦4 小时前
从零起步学习Redis || 第十章:主从复制的实现流程与常见问题处理方案深层解析
java·服务器·数据库·redis·后端·缓存
极限实验室5 小时前
Elasticsearch 备份:snapshot 镜像使用篇
数据库·elasticsearch