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;
相关推荐
吴声子夜歌7 分钟前
ES6——正则的扩展详解
前端·mysql·es6
xixingzhe213 分钟前
Mysql统计空间增量
数据库·mysql
程序员萌萌19 分钟前
Java之mysql实战讲解(三):聚簇索引与非聚簇索引
java·mysql·聚簇索引
程序员萌萌1 小时前
Redis的缓存机制和淘汰策略详解
数据库·redis·缓存机制·淘汰策略
不剪发的Tony老师1 小时前
SQLite 3.53.0版本发布,重要更新
数据库·sqlite
Bczheng11 小时前
九.Berkeley DB数据库 序列化和钱包管理(1)
数据库
cozil1 小时前
记录mysql创建数据库未指定字符集引发的问题及解决方法
数据库·mysql
架构师老Y2 小时前
013、数据库性能优化:索引、查询与连接池
数据库·python·oracle·性能优化·架构
AC赳赳老秦2 小时前
OpenClaw数据库高效操作指南:MySQL/PostgreSQL批量处理与数据迁移实战
大数据·数据库·mysql·elasticsearch·postgresql·deepseek·openclaw
一 乐2 小时前
校园线上招聘|基于springboot + vue校园线上招聘系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·校园线上招聘系统