数据库的操作
sql语句要以分号 ; 结尾
显示数据库版本
select version();显示时间
select now();查看所有数据库
show databases;创建数据库
-- create database 数据库名 charset=utf8;
create database school;
create database school charset=utf8;查看创建数据库的语句
-- show crate database 数据库名;
show create database school;查看当前使用的数据库
select database();使用数据库
-- use 数据库名;
use school;删除数据库
-- drop database 数据库名;
drop database school;数据表的操作
查看当前数据库中所有表
show tables;创建表
-- auto_increment 表示自动增长
-- not null 表示不能为空
-- primary key 表示主键
-- default 默认值
-- create table 数据表名字 (字段 类型 约束, 字段 类型 约束, ...);
create table students (
id int unsigned not null auto_increment primary key,
name varchar(30),
age tinyint unsigned default 0,
height decimal(5, 2),
gender enum("男", "女", "保密") default "保密"
);查看表结构
-- desc 表名;
desc students;查看表的创建语句
-- show create table 表名字;
show create table students;修改表结构
-- 添加字段
-- alter table 表名 add 字段名 类型;
alter table students add birthday datetime;
-- 修改字段
-- alter table 表名 modify 字段名 类型及约束;
alter table students modify birthday date;
-- 修改字段以及字段名
-- alter table 表名 change 字段原名 字段新名 类型及约束;
alter table students change birthday birth date default "2000-01-01";
-- 删除字段
-- alter table 表名 drop 字段名;
alter table students drop birth;删除表
-- drop table 表名;
drop table students;增删改查(curd)
curd: 创建(Create)、更新(Update)、读取(Retrieve)和删除(Delete)
查询 (select语句)
-- 查询所有字段
-- select * from 表名;
select * from students;
-- 查询指定字段
-- select 字段1, 字段2, ... from 表名;
select id, name from students;
-- 指定条件查询
select * from students where name = "小明"; -- 查询name为小明的所有信息
select * from students where id > 3; -- 查询id>3所有信息
-- 查询时可以使用as为字段获表指定别名
select name as 姓名, age as 年龄 from students;
-- 查询时可以使用distinct消除重复行
select distinct gender from students;增加 (insert语句)
-- 全列插入
-- insert into 表名 values(...)
-- 主键自动增长时, 在全列插入时需要占位,通常使用0或default或null来占位
insert into students values(0, "小明", 20, 170.00, "男" );
-- 部分插入
-- insert into 表名(字段1, 字段2...) values(值1, 值2...)
insert into students (name, gender) values ("小红", 2);
-- 多行插入
insert into students (name, gender) values ("小乔", 2), ("貂蝉", 2);
insert into students values(default, "西施", 19, 165.00, "女"),
(default, "王昭君", 18, 169.00, "女");修改 (update语句)
-- update 表名 set 字段1 = 值1, 字段2 = 值2... where 条件;
update students set gender = 1; -- 全部修改
update students set gender = 2 where name = "小明"; -- 只要name是小明的全部修改
update students set gender = 1 where id = 3; -- 只要id为3的进行修改
update students set age = 20, gender = 1 where id = 3; -- 只要id为3的进行修改删除 (delete语句)
-- 物理删除
-- delete from 表名 where 条件;
delete from students; -- 整个数据表中的所有数据全部删除
delete from students where name = "小明"; -- 删除name为小明的记录
-- 逻辑删除
-- 用一个字段来表示这条信息是否已经不能再使用了
-- 给students表添加一个is_delete字段, bit类型 0: 表示存在; 1: 表示删除
alter table students add is_delete bit default 0;
update students set is_delete = 1 where id = 6;本文作者: Ifan Tsai (菜菜)
本文链接: https://www.caiyifan.cn/p/48503.html
版权声明: 本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!
未经允许不得转载:便宜VPS » MySQL常用sql语句