— sql 结构化查询语言 操作数据库的
— 注释 –空格
— 创建数据库
create database itquanmingxing;
— 创建数据库的时候设置编码
create database itquanmingxing2 CHARACTER set utf8;
— 删除数据库
drop database itquanmingxing;
— 删除数据库前 先判断数据库是否存在
drop database if exists itquanmingxing;
— 使用库
use itquanmingxing2;
— 创建表
create table teacher
(
tid int primary key ,
tname varchar(2),
professional_title varchar(20)
);
— 打印表结构
desc teacher;
— 查询表数据
select * from teacher;
— 删除表
drop table teacher;
drop table if exists teacher;
create table teacher
(
tid int primary key auto_increment, — 自增 默认从1开始 每次自增1
tname varchar(2),
professional_title varchar(20)
)ENGINE=INNODB default charset=utf8 auto_increment=100; — 自增 从100开始
select * from teacher;
— 修改表
— 添加列
alter table teacher — 修改 表 表名
add salary float — 添加 列名 列的属性
— 删除列
alter table teacher
drop column salary — 删除 列 列名
— 修改列
alter table teacher
modify column tname varchar(20) — 修改 列 列名 列的属性
desc teacher;
— 给表添加约束
create table student
(
sid int primary key auto_increment, — 主键约束
sname varchar(20) not null, — 非空约束
sex char(2) default ‘男’, — 默认约束
card_id char(18) unique, — 唯一约束
age int, — check(age>=18 and age
foreign key(tid) REFERENCES teacher(tid) — 外键约束 必须是其它表中的主键
)ENGINE=INNODB;
select * from teacher;
select * from student;
— 实体完整性: 主键约束 唯一约束
— 域完整性 : not null default
— 引用完整性: 外键
— insert 添加数据
select * from teacher;
— 添加表中的所有列
insert into teacher values(null,’daimenglaoshi’,’高级’);
— 添加部分列
insert into teacher(tname) values(‘wanglaoshi’);
insert into teacher values(null,’zhanglaoshi’,’高级’);
insert into student values(null,’lisi’,default,556777,null,101);
insert into student values(null,’wangwu’,default,888888,null,102);
insert into student values
(null,’zhaoliu’,default,99999,null,101),
(null,’王二’,default,77777,null,102);
— update 更新
— 语法: update 表名 set 新的值 where 条件
— 将王五的性别改为女
update student set sex=’女’ where sname=’wangwu’
— 将所有年龄为null的学生的年龄改为28
update student set age=28 where age is null;
select * from student;
— 将所有的年龄都清空
update student set age = null;
— 将学号在2–5范围内的学生的年龄改为18
update student set age=18 where sid>=2 and sid
Original: https://www.cnblogs.com/daimenglaoshi/p/16853018.html
Author: 呆萌老师
Title: SQL增删查改
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/714341/
转载文章受原作者版权保护。转载请注明原作者出处!