-- DDL
USE db1;
SHOW TABLES;
# 添加字段
ALTER TABLE students ADD brithday DATETIME DEFAULT "2020-07-21";
ALTER TABLE students ADD id_2 INT;
# 修改字段
ALTER TABLE students MODIFY brithday DATE DEFAULT "2020-07-21";
# 修改字段名
ALTER TABLE students CHANGE brithday birth DATE DEFAULT "2020-07-21";
# 删除字段
ALTER TABLE students DROP id_2;
-- DML 表数据操作
# 添加整行数据
INSERT INTO students VALUE(10, "lily", 20, "2000-1-1");
# 同时添加多行数据
INSERT INTO students(NAME, age, birth, gender) VALUES("lucy", 21, "1999-01-01", "male"),
("jerry", 25, "1995-01-01", "male"),
("ermao", 10, "2010-01-01", "female");
# 添加name,gender两个字段的数据
ALTER TABLE students ADD gender ENUM("male","female");
# 将姓名为jacky全部修改为jack
UPDATE students SET NAME="jack" WHERE NAME="jacky";
# 将性别为女的名字修改为rose
UPDATE students SET NAME="rose" WHERE gender="female";
# 将姓名为jack的数据 物理删除
DELETE FROM students WHERE NAME="jack";
-- 查询语句
# 查询Student表所有数据
SELECT * FROM students;
# 询Student表中name与gender字段的数据
SELECT NAME, gender FROM students;
# 查询Student表中name字段的数据并且去重
SELECT DISTINCT NAME FROM students;
-- 比较运算: = > >= < <= <> !=
# 查询id大于11的数据
SELECT * FROM students WHERE id>11;
# 查询年龄大于18岁的信息
SELECT * FROM students WHERE age>18;
# 查询姓名不是lily的数据
SELECT * FROM students WHERE NAME!="lily";
-- 逻辑运算: and or not
# 查询18~22之间的所有学生信息
SELECT * FROM students WHERE age>=18 AND age<=22;
# 查询id大于3的女同学
SELECT * FROM students WHERE id>3 AND gender="female";
# 查询id小于12或者id大于13的学生信息
SELECT * FROM students WHERE id<12 OR id>13
# 查询年龄不是18的女同学
SELECT * FROM students WHERE (NOT age=18) AND gender="female";
-- like % _
# 查询名字以l开始的学生信息
SELECT * FROM students WHERE NAME LIKE("l%");
# 查询名字含有i的学生信息
SELECT * FROM students WHERE NAME LIKE("%i%");
# 查询名字仅有2个字符的学生信息
INSERT INTO students(NAME, age) VALUES("wb", 11);
SELECT * FROM students WHERE NAME LIKE("__");
# 查询名字至少有2个字符的学生信息
INSERT INTO students(NAME, age) VALUE("o", 111);
SELECT * FROM students WHERE NAME LIKE("__%");
-- in 和 between and
# 查询id是1或者11或者13的学生信息
SELECT * FROM students WHERE id IN(1,11,13);
# 查询年龄不是18,20的学生信息
SELECT * FROM students WHERE age NOT IN(18,20);
# 查询id是2至4的学生信息
SELECT * FROM students WHERE id BETWEEN 2 AND 4;
# 查询id是3-5的男同学信息
SELECT * FROM students WHERE (id BETWEEN 10 AND 15) AND gender="male";
# 查询年龄不在18至20之间的学生信息
SELECT * FROM students WHERE age NOT BETWEEN 18 AND 20;
-- is null 和 is not null
# 查询没有填写性别的学生
SELECT * FROM students WHERE gender IS NULL;
SELECT * FROM students WHERE gender IS NOT NULL;
-- 聚合函数
# 查询最大的年龄
SELECT MAX(age) AS "最大年龄" FROM students;
# 女性最大的id
SELECT MAX(id) FROM students WHERE gender="female";
# 查询未删除的学生的最小编号
ALTER TABLE students DROP is_delete;
ALTER TABLE students ADD is_delete ENUM ("0","1") DEFAULT "1";
SELECT MIN(id) FROM students WHERE is_delete="0";
# 查询男生年龄和
SELECT SUM(age) FROM students WHERE gender="male";
# 查询未删除女生的年龄的平均值 保留一位小数
SELECT ROUND(AVG(age), 1) FROM students WHERE gender="female" AND is_delete="1";
# 计算男性的平均年龄,保留2位小数
SELECT ROUND(AVG(age), 2) FROM students WHERE gender="female";