Table of contents
Basic Data Manipulation (CRUD)
basic data type
Integer: optional unsigned modification
intyint 8 bits (-128 - 127)
smallint 16 bits (-32768 - 32767)
mediumint 24 bits (-8388608 - 8388607)
int 32 bits about plus or minus 2.1 billion
bigint 64 bits
Real numbers (with decimal point): approximate calculations using standard floating-point arithmetic
float 4 bytes
double 8 bytes
decimal allows up to 65 digits
Example: decimal(5,2), description: 5 digits length, 2 digits of decimal precision, if the integer part + 2 digits of decimals is too long, an error will be reported, if Only if the decimal part exceeds 2, it will be rounded to two decimal places
string
char : fixed length: msql allocates enough space at one time according to the length of the defined string
Applicable scenarios: shorter strings, and all values are close to the same lengthvarchar variable length string
- Saves space compared to fixed-length types
- But ROW_FOMAT=FIXED use fixed length for each row
- Applicable scenarios: the maximum length of the string is much larger than the evaluation length, and the column is updated less
- Disadvantages: page splitting may occur when frequent modifications and large changes in the length of the string
- Do not blindly give excessive length
- May encounter maximum length allocation memory issues in temporary tables or sorting
Text、Blob
1. Both are designed to store large data
2. Different from other data, they are stored as independent objects
3. When the value is too large, use the external storage area to store, only use 1-4 bytes for each row to store a pointer
text stores character data : tinytext
smalltext
text
mediumtext
longtext
Blobs store binary data : tinyblob
smallblob
blob
mediumblob
longblob
datetime
datetime
precision: seconds
independent of time zone, 8 bytes storage
range: 1001 to 9999 yearstimestamp
saves the number of seconds since midnight on January 1, 1970,
occupies 4 bytes of storage space
. Range: 1970 to 2038
is related to time zone.
Default is NOT NULL .
Usually try to use timestamp
precision: secondsdate
yyyy-MM-ddtime
HH:mm:ss
select identifier
- used to associate
- as foreign key in other table
- Integers are usually the best choice for identity columns
- Use the same data type in related tables
- Try to avoid strings as identity columns, especially randomly generated strings (such as: uuid) cause both insert and select to be slow
- Inserted values are randomly written to different positions of the index. Inserts are slow and easily lead to page splits and random disk reads.
- Logically adjacent rows are distributed in different places on disk and in memory, and select is slow
- Invalidate mysql query cache
- If you need to store uuid, you should remove "-"
(Insert values are randomly written to different positions in the index, insert is slow, and it is easy to cause page splits, disk random reads
logically adjacent rows are distributed in different places on disk and memory, slow select
makes mysql query cache invalid .
If you need to store uuid, "-" should be removed)
database command
Create the database:
create database 数据库名 create database if not exists 数据库名 default charset utf8 collate utf8_general_ci; //默认的数据库编码集:utf8 //collate表示校验规则为utf8_general_ci //常用排序类型 //utf8_general_cs(区分大小写) //utf8_genera_ci(不区分大小写)
View all databases:
show databases
Delete the database:
drop database 数据库名
Note: Deleting the database is a dangerous operation, if you want to delete it, it is recommended to back it up first
Create tables and constraints
build table
Command format: create table table name (
column name 1 data type not null,
column name 2 data type,
column name 3 data type,
unique(column name 1[, column name 2,..., column name N])
)Example:
create table t_student ( sid int not null comment '学号', sname varchar(60) not null comment '姓名', sex tinyint not null default 1 comment '性别:1男, 2女', age tinyint not null comment ' 年龄', icard varchar(18) not null comment '身份证,唯一约束', primary key (sid), unique key AK_Key_2 (icard) ) comment '学生信息表';
constraint
Primary key constraint: primary key
add primary key (alter table table name add primary key (primary key name))
delete primary key (alert table table name drop primary key)
non-empty constraint:sid int not null comment'学号',
Foreign key constraints:
create table t_score ( id int not null comment'记录流水号', sid int not null comment'学号', cid int not null comment'课程ID', score float comment'成绩', primary key(id), foreign key(sid) references t_student (sid) on delete restrict on update redtrict , unique key ak_key_2(sid, cid) ); //说明: sid为本表的外键,关联t_student表中的的sid主键,on delete restrict on update redtrict说明在本表有数据的情况下,主表的关联键不能删除或更新。
Add primary key (alert table table name add foreign key (foreign key name) references main table name (primary key name))
Delete the primary key (alert table table name drop foreign key constraint name)
Unique constraint: unique key constraint name (field)
Create a unique constraint: alert table table name add unique (column name 1[, column name 2, ..])
create unique index UserNameIndex on 't_user' ('username')
Delete unique constraint: alert table table name drop index unique constraint epitome name
Default value constraint: default
Basic Data Manipulation (CRUD)
data preparation
create database db_t281
use db_t281
-- 1.学生表-t_student
-- sid 学生编号,sname 学生姓名,sage 学生年龄,ssex 学生性别
create table t_student
(
sid int not null auto_increment comment '学号',
sname varchar(40) not null comment '名称',
birthday date not null comment '年龄',
ssex tinyint not null default 1 comment '1男,2女',
primary key (sid)
);
INSERT INTO t_student VALUES(1, '赵雷' , '1990-01-01' , 1);
INSERT INTO t_student VALUES(2 , '钱电' , '1990-12-21' , 1);
INSERT INTO t_student VALUES(3 , '孙风' , '1990-12-20' , 1);
INSERT INTO t_student VALUES(4 , '李云' , '1990-12-06' , 1);
INSERT INTO t_student VALUES(5 , '周梅' , '1991-12-01' , 2);
INSERT INTO t_student VALUES(6 , '吴兰' , '1992-01-01' , 2);
INSERT INTO t_student VALUES(7 , '郑竹' , '1989-01-01' , 2);
INSERT INTO t_student VALUES(9 , '张三' , '2017-12-20' , 2);
INSERT INTO t_student VALUES(10 , '李四' , '2017-12-25' , 2);
INSERT INTO t_student VALUES(11 , '李四' , '2012-06-06' , 2);
INSERT INTO t_student VALUES(12 , '赵六' , '2013-06-13' , 2);
INSERT INTO t_student VALUES(13 , '孙七' , '2014-06-01' , 2);
-- 2.教师表-t_teacher
-- tid 教师编号,tname 教师名称
CREATE TABLE t_teacher
(
tid INT NOT NULL AUTO_INCREMENT COMMENT '教师ID',
tname VARCHAR(40) NOT NULL COMMENT '教师名称',
PRIMARY KEY (tid)
);
INSERT INTO t_teacher VALUES(1 , '张五哥');
INSERT INTO t_teacher VALUES(2 , '李卫');
INSERT INTO t_teacher VALUES(3 , '年羹尧');
-- 3.课程表-t_course
-- cid 课程编号,cname 课程名称,tid 教师名称
CREATE TABLE t_course
(
cid INT NOT NULL COMMENT '课程ID',
cname VARCHAR(50) COMMENT '课程名称',
tid INT COMMENT '教师id',
PRIMARY KEY (cid)
);
INSERT INTO t_course VALUES(1 , '语文' , 2);
INSERT INTO t_course VALUES(2 , '数学' , 1);
INSERT INTO t_course VALUES(3 , '英语' , 3);
-- 4.成绩表-t_score
-- sid 学生编号,cid 课程编号,score 成绩
CREATE TABLE t_score
(
sid INT NOT NULL COMMENT '学号,外键',
cid INT NOT NULL COMMENT '课程id',
score decimal(5,2) COMMENT '成绩',
UNIQUE KEY ak_key_sid_cid (sid, cid)
);
INSERT INTO t_score VALUES(1 , 1 , 80);
INSERT INTO t_score VALUES(1 , 2 , 90);
INSERT INTO t_score VALUES(1 , 3 , 99);
INSERT INTO t_score VALUES(2 , 1 , 70);
INSERT INTO t_score VALUES(2 , 2 , 60);
INSERT INTO t_score VALUES(2 , 3 , 80);
INSERT INTO t_score VALUES(3 , 1 , 80);
INSERT INTO t_score VALUES(3 , 2 , 80);
INSERT INTO t_score VALUES(3 , 3 , 80);
INSERT INTO t_score VALUES(4 , 1 , 50);
INSERT INTO t_score VALUES(4 , 2 , 30);
INSERT INTO t_score VALUES(4 , 3 , 20);
INSERT INTO t_score VALUES(5 , 1 , 76);
INSERT INTO t_score VALUES(5 , 2 , 87);
INSERT INTO t_score VALUES(6 , 1 , 31);
INSERT INTO t_score VALUES(6 , 3 , 34);
INSERT INTO t_score VALUES(7 , 2 , 89);
INSERT INTO t_score VALUES(7 , 3 , 98);
select * from t_student;
select * from t_teacher;
select * from t_course;
select * from t_score;
The data table is as follows:
t_student student table t_teacher teacher table
t_course curriculum t_score score table
1) Query the information and course scores of students whose grades in the "1" course are higher than those in the "2" course
SELECT stu.sid,stu.sname,stu.ssex,c1.cid, c1.score, c2.cid, c2.score FROM t_student stu INNER JOIN (SELECT t1.sid, t1.cid, t1.score FROM t_score t1 WHERE t1.cid = 1 ) c1 ON stu.sid = c1.sid INNER JOIN (SELECT t2.sid, t2.cid, t2.score FROM t_score t2 WHERE t2.cid = 2) c2 ON stu.sid = c2.sid WHERE c1.score > c2.score
2) Query the information of students who take both "1" courses and "2" courses
//方法一 SELECT stu.sid,stu.sname,stu.ssex,c1.cid, c1.score, c2.cid, c2.score FROM t_student stu INNER JOIN (SELECT t1.sid, t1.cid, t1.score FROM t_score t1 WHERE t1.cid = 1 ) c1 ON stu.sid = c1.sid INNER JOIN (SELECT t2.sid, t2.cid, t2.score FROM t_score t2 WHERE t2.cid = 2) c2 ON stu.sid = c2.sid //方法二 SELECT stu.`sid`,stu.`sname`, stu.`ssex`, tmp.c1num, tmp.c2num FROM t_student stu INNER JOIN ( SELECT t.`sid`, SUM(CASE WHEN t.cid = 1 THEN t.`score` ELSE 0 END) c1num, SUM(CASE WHEN t.cid = 2 THEN t.`score` ELSE 0 END) c2num FROM t_score t GROUP BY t.`sid` ) tmp ON stu.sid = tmp.sid AND tmp.c1num > 0 AND tmp.c2num > 0;
3) Inquire about elective "1" courses but not elective "2" courses
SELECT stu.* FROM t_student stu WHERE stu.sid IN(SELECT t1.sid FROM t_score t1 WHERE t1.cid = 1) AND stu.sid NOT IN (SELECT t1.sid FROM t_score t1 WHERE t1.cid = 2) SELECT stu.`sid`,stu.`sname`, stu.`ssex`, tmp.c1num, tmp.c2num FROM t_student stu INNER JOIN ( SELECT t.`sid`, SUM(CASE WHEN t.cid = 1 THEN t.`score` ELSE 0 END) c1num, SUM(CASE WHEN t.cid = 2 THEN t.`score` ELSE 0 END) c2num FROM t_score t GROUP BY t.`sid` ) tmp ON stu.sid = tmp.sid AND tmp.c1num > 0 AND tmp.c2num = 0;
4) Query the case where "1" course does not exist but "2" course exists
SELECT t1.sid,t1.cid,t1.score FROM t_score t1 WHERE t1.cid = 2 AND t1.sid NOT IN (SELECT t2.sid FROM t_score t2 WHERE t2.cid = 1);
Query the highest score, lowest score and average score of each subject:
1) Display column: course ID, course name, highest score, lowest score, average score, number of electives, pass rate, average rate, excellent rate
2) The excellent rate is >=60, medium: 70-80, excellent: 80-90, excellent: >=90
3) The query results are required to be sorted in descending order by number of people.SELECT t2.cid '课程ID', t2.cname '课程名称', MAX(t1.score) '最高分', MIN(t1.score) '最低分', ROUND(AVG(t1.score), 2) '平均分', COUNT(t1.sid) '选修人数', ROUND(SUM(CASE WHEN t1.score >= 60 THEN 1 ELSE 0 END) / COUNT(t1.sid), 2) '及格率', ROUND(SUM(CASE WHEN t1.score >=70 AND t1.score < 80 THEN 1 ELSE 0 END)/COUNT(t1.sid),2) '中等率', ROUND(SUM(CASE WHEN t1.score >=80 AND t1.score < 90 THEN 1 ELSE 0 END)/COUNT(t1.sid),2) '优良率', ROUND(SUM(CASE WHEN t1.score >= 90 THEN 1 ELSE 0 END)/COUNT(t1.sid), 2) '优秀率' FROM t_score t1 INNER JOIN t_course t2 ON t1.cid = t2.cid GROUP BY t2.cid, t2.cname ORDER BY COUNT(t1.sid) DESC, t2.cid ASC;