当前位置:网站首页>Stage 4 MySQL database
Stage 4 MySQL database
2022-07-06 11:35:00 【@Little snail】
Catalog
- Learning website
- 4-1MySQL database - First time to know MySQL
- 4-2MySQL database - Basic operation of database and table ( One )
- The first 1 Turn off : View the table structure and modify the table name
- The first 2 Turn off : Modify the field name and field data type
- The first 3 Turn off : Add and delete fields
- The first 4 Turn off : Change the arrangement of fields
- The first 5 Turn off : Delete foreign key constraint of table
- 4-3MySQL database - Basic operation of database and table ( Two )
- 4-4MySQL database - Single table query ( One )
- 4-5MySQL database - Single table query ( Two )
- 4-6MySQL database - Single table query ( 3、 ... and )
- 4-7MySQL database - Use aggregate functions to query
- 4-8MySQL database - Link query
- 4-9MySQL database - Subquery
- 4-10MySQL database - Group selection data
- 4-11MySQL Development skills - Paging and indexing
- 4-12 Database design - The blog system
- 4-13 Database query - Course selection system
Learning website
Click here to jump :https://www.educoder.net/shixuns/rx56kula/challenges
4-1MySQL database - First time to know MySQL
Enter the command :mysql -u user name -p password
To connect to the database on the platform, you need to add -h127.0.0.1.
mysql -uroot -p123123 -h127.0.0.1
create database MyDb;
show databases;
Be careful not to forget the semicolon at the end ;
The first 2 Turn off : Create table
The data in the database is stored in tables one by one .
You can imagine that the database is like a folder , And the table can be understood as a excel form , In fact, they are quite similar .
mysql -uroot -p123123 -h127.0.0.1
create database TestDb;
show databases;
use TestDb;
create table t_emp (
id Int,
name VARCHAR(32),
deptId Int,
salary FLOAT
);
desc t_emp;
The first 3 Turn off : Use primary key constraints
mysql -uroot -p123123 -h127.0.0.1
create database MyDb;
show databases;
use MyDb;
create table t_user1 (
userId Int PRIMARY KEY,
name VARCHAR(32),
password VARCHAR(11),
phone VARCHAR(11),
email VARCHAR(32)
);
desc t_user1;
create table t_user2 (
name VARCHAR(32),
phone VARCHAR(11),
email VARCHAR(32),
PRIMARY KEY(name,phone)
);
desc t_user2;
The first 4 Turn off : Foreign key constraints
mysql -uroot -p123123 -h127.0.0.1
create database MyDb;
show databases;
use MyDb;
create table t_class(
id Int PRIMARY KEY,
name VARCHAR(22)
);
desc t_class;
create table t_student(
id Int PRIMARY KEY,
name VARCHAR(22),
classId Int,
CONSTRAINT fk_stu_class1 FOREIGN KEY(classId) REFERENCES t_class(Id)
);
desc t_student;
The first 5 Turn off : Add common constraints
Set the property value of the table to increase automatically AUTO_INCREMENT
mysql -uroot -p123123 -h127.0.0.1
create database MyDb;
show databases;
use MyDb;
create table t_user(
id Int PRIMARY KEY auto_increment,
username VARCHAR(32) not null unique,
sex VARCHAR(4) default ' male '
)DEFAULT CHARSET=utf8;
4-2MySQL database - Basic operation of database and table ( One )
The first 1 Turn off : View the table structure and modify the table name
The grammar rule is :DESCRIBE Table name ;
Case insensitive !
Let me tell you a little trick , Do you think the layout of the returned results is a little messy . We add \G The effect will be improved after , Let's see !
USE Company;
# Please add the implementation code here
########## Begin ##########
########## modify the table name ##########
alter table tb_emp rename jd_emp;
########## show tables in this database ##########
show tables;
########## describe the table ##########
desc jd_emp;
########## End ##########
The first 2 Turn off : Modify the field name and field data type
USE Company;
# Please add the implementation code here
########## Begin ##########
########## change the column name ##########
alter table tb_emp change Id prod_id int(11);
########## change the data type of column ##########
alter table tb_emp modify Name varchar(30);
########## End ##########
DESCRIBE tb_emp;
The first 3 Turn off : Add and delete fields
USE Company;
# Please add the implementation code here
########## Begin ##########
########## add the column ##########
alter table tb_emp add Country varchar(20) after Name;
########## delete the column ##########
alter table tb_emp drop Salary;
########## End ##########
DESCRIBE tb_emp;
The first 4 Turn off : Change the arrangement of fields
USE Company;
# Please add the implementation code here
########## Begin ##########
########## modify the column to top ##########
alter table tb_emp modify Name varchar(25) first;
########## modify the column to the rear of another column ##########
alter table tb_emp modify DeptId int(11) after Salary;
########## End ##########
DESCRIBE tb_emp;
The first 5 Turn off : Delete foreign key constraint of table
USE Company;
# Please add the implementation code here
########## Begin ##########
########## delete the foreign key ##########
alter table tb_emp drop FOREIGN KEY emp_dept;
########## End ##########
SHOW CREATE TABLE tb_emp \G;
4-3MySQL database - Basic operation of database and table ( Two )
The first 1 Turn off : insert data
Insert a column
ERROR 1062 (23000) at line 8: Duplicate entry ‘0’ for key ‘PRIMARY’
reason : Two primary key fields are 0 The record of , Conflict .( Set primary key auto increment solution )( duplicate repeat )
USE Company;
# Please add the implementation code here
########## Begin ##########
########## bundle insert the value ##########
insert into tb_emp (Id,Name,DeptId,Salary)
values(1,'Nancy',301,2300),(2,'Tod',303,5600),(3,'Carly',301,3200);
########## End ##########
SELECT * FROM tb_emp;
The first 2 Turn off : Update data
UPDATE Mall_products2
SET country_name = "Pakistan", country_id = 92
WHERE id = 2;
USE Company;
# Please add the implementation code here
########## Begin ##########
########## update the value ##########
update tb_emp
set Name="Tracy",DeptId=302,Salary=4300.00
where Id = 3;
########## End ##########
SELECT * FROM tb_emp;
Be careful : Add a semicolon to the last sentence ; secondly , Single and double quotation marks should be distinguished
The first 3 Turn off : Delete data
Operate on the table , use drop
Opposite operation , use delete
4-4MySQL database - Single table query ( One )
The first 1 Turn off : Basic query statement
The first 2 Guan Dai IN Keyword query
The first 3 Guan Dai BETWEEN AND The scope of inquiry
4-5MySQL database - Single table query ( Two )
The first 1 Guan Dai LIKE Character matching query for
The first 2 Query null values and remove duplicate results
USE Company;
######### Begin #########
select *
from tb_emp
where DeptId is null;
######### End #########
######### Begin #########
select distinct Name
from tb_emp;
######### End #########
The first 3 Guan Dai AND And OR Multi criteria query of
USE Company;
######### Begin #########
# Use keywords AND Return the fields in the data table DeptId by 301 And the salary is greater than 3000 The contents of all fields of the ,
select *
from tb_emp
where DeptId=301 and Salary>3000;
######### End #########
######### Begin #########
# Use keywords IN Return the fields in the data table DeptId by 301 and 303 The contents of all fields of the .
select *
from tb_emp
where DeptId in (301,303);
######### End #########
4-6MySQL database - Single table query ( 3、 ... and )
The first 1 Sort query results
SELECT Field name FROM Table name ORDER BY Field name [ASC[DESC]];
ASC Ascending keywords
DESC Descending keywords
The first 2 Group query
The first 3 Off use LIMIT Limit the number of query results
USE School;
# Please add the implementation code here
########## Begin ##########
########## Query the... In the class 2 Name to number 5 Student information of name ##########
select *
from tb_score
order by score desc
limit 1,4;# Start with the second record and look back 4 Data ( Does not include the first ):
########## End ##########
4-7MySQL database - Use aggregate functions to query
The first 1 Turn off :COUNT( ) function
USE School;
# Please add the implementation code here
########## Begin ##########
########## Query the total number of data in the table ##########
select count(*)
from tb_class;
########## Query... In this table 367 How many students are there in the class ##########
select classid,count(*)
from tb_class
where classid=367;
########## End ##########
The first 2 Turn off SUM( ) function
USE School;
# Please add the implementation code here
########## Begin ##########
########## Query the total score of all students ##########
select sum(score)
from tb_class;
########## Query the total score of students' Chinese subjects ##########
select course,sum(score)
from tb_class
where course=" Chinese language and literature ";
########## End ##########
The first 3 Turn off AVG( ) function
The first 4 Turn off MAX( ) function
The first 5 Turn off MIN( ) function
4-8MySQL database - Link query
The first 1 Connection query inside the customs
USE School;
########## Query the students' names and corresponding classes in the data table ##########
# Please add the implementation code here
########## Begin ##########
select tb_student.name as studentName, tb_class.name as className
from tb_student join tb_class
on tb_student.class_id=tb_class.id;
########## End ##########
The first 2 External connection query
USE School;
########## Use the left outer connection to query the names of all students and the corresponding classes ##########
# Please add the implementation code here
########## Begin ##########
select tb_student.name as studentName, tb_class.name as className
from tb_student left join tb_class
on tb_student.class_id=tb_class.id;
########## End ##########
########## Use the right external connection to query all student names and corresponding classes ##########
# Please add the implementation code here
########## Begin ##########
select tb_student.name as studentName, tb_class.name as className
from tb_student right join tb_class
on tb_student.class_id=tb_class.id;
########## End ##########
The first 3 About compound conditional connection query
USE School;
########## Check the scores of all classes in 90 The name of the student with a score of above, the student's grade and the class in which the student belongs ##########
# Please add the implementation code here
########## Begin ##########
select tb_student.name as studentName, score,tb_class.name as className
from tb_student left join tb_class
on tb_student.class_id=tb_class.id
where score>90
order by score desc;
########## End ##########
4-9MySQL database - Subquery
The first 1 Subqueries with comparison operators
USE Company;
# Please add the implementation code here
########## Begin ##########
#1. Query the name and age of employees older than all average ages
select name,age
from tb_emp
where age>all(
select avg(age)
from tb_emp);
########## End ##########
The first 2 Keyword subquery
USE Company;
# Please add the implementation code here
########## Begin ##########
#1. Use ALL Keyword query
select position,salary
from tb_salary
where salary>all(
select max(salary)
from tb_salary
where position="Java"
);
#2. Use ANY Keyword query
select position,salary
from tb_salary
where salary>ANY(
select min(salary)
from tb_salary
where position="Java"
);
#3. Use IN Keyword query
select position,salary
from tb_salary
where salary in (
select salary
from tb_salary
where position="Java"
);
########## End ##########
4-10MySQL database - Group selection data
The first 1 Turn off GROUP BY And Aggregate functions
USE School;
# Please add the implementation code here
########## Begin ##########
#1. In the query table 2,3,4 The total number of men and women in each grade
select gradeId,sex,count(*)
from student
where gradeId in(2,3,4)
group by gradeId,sex;
########## End ##########
The first 2 Off use HAVING And ORDER BY
USE School;
# Please add the implementation code here
########## Begin ##########
#1. There are at least two courses in the query table 90 Information of students with scores above
select sno,count(*)
from tb_grade
where score>=90
group by sno
having count(*)>=2;
#2. The average score in the query table is greater than 90 And the Chinese class is in 95 Information of students with scores above
select sno,avg(score)
from tb_grade
where sno in(
select distinct sno
from tb_grade
where pno=" Chinese language and literature " and score>=95)
group by sno
having avg(score)>=90;
########## End ##########
4-11MySQL Development skills - Paging and indexing
The first 1 Turn off MySQL Paging query
USE Products;
# Please add the implementation code here
########## Begin ##########
#1. Paging query
select prod_id
from products
limit 5,5;
#2. Optimize paging query statements with subqueries
select prod_id
from products
where prod_id >=(
select prod_id
from products
limit 10,1
)
limit 5;
########## End ##########
The first 2 Off index ( Single index )
Single column index classification and creation
The most common one we use is single column index , It is divided into primary key index 、 Common index and unique index .
USE Students;
# Please add the implementation code here
########## Begin ##########
#1. establish student Table structure and set id Index for primary key
CREATE TABLE student(
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
score int(10),
PRIMARY KEY (id)
);
#2. Yes name Build unique index
CREATE unique INDEX name_index on `student`(`name`);
#3. Yes score Build a normal index
CREATE INDEX score_index on `student`(`score`);
SHOW INDEX FROM student;
########## End ##########
The first 3 Off index ( Composite index )
4-12 Database design - The blog system
-- Create database
CREATE DATABASE blog_db;
use blog_db;
-- stay blog_db Create... In the library t_user surface
-- User information sheet
CREATE TABLE t_user
(
userId BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT ' user ID',-- The low version programming environment does not recognize AUTO_INCREMENT, Switch to IDENTITY(1,1)
username VARCHAR(32) NOT NULL COMMENT' user name ',--COMMENT remarks
password VARCHAR(32) NOT NULL COMMENT' password ',
user_sex VARCHAR(6) NOT NULL DEFAULT '0' COMMENT' Gender 0 For men 1 For women ',-- Set the default value DEFAULT
email VARCHAR(64) COMMENT' mailbox ',
phone VARCHAR(11) NOT NULL COMMENT' Phone number ',
firstname VARCHAR(6) COMMENT' surname ',
lastname VARCHAR(12) COMMENT' name ',
avatar VARCHAR(255) COMMENT' Head portrait address ',
is_superuser INT(11) NOT NULL DEFAULT 0 COMMENT' Administrator or not 0 It means no 1 Representative is ',
last_login DATETIME COMMENT' Last login time ',
user_register_time DATETIME COMMENT' Last login time ',
PRIMARY KEY (userId)-- Primary key
);
/* establish blog_type、t_blog、t_comment surface , And establish the relationship between tables. Blog type table and blog information table are one to many relationships , Blog comment table and blog information table are many to one , User information table and blog information table 、 Blog comment table is a one to many relationship .*/
-- Blog type table
CREATE TABLE blog_type
(
type_id INT NOT NULL AUTO_INCREMENT COMMENT' type id',
type_name VARCHAR(32) NOT NULL COMMENT' Type the name ',
PRIMARY KEY(type_id)
);
-- Blog information table
CREATE TABLE t_blog
(
blog_id BIGINT NOT NULL AUTO_INCREMENT COMMENT' Blog id',
blog_title VARCHAR(100) NOT NULL COMMENT' Blog title ',
blog_content LONGTEXT NOT NULL COMMENT' Blog content ',
userid BIGINT COMMENT' founder id',
type_id INT COMMENT' type id',
blog_status INT NOT NULL DEFAULT '0' COMMENT' Blog status 1 For the release of 0 For draft ',
create_time DATETIME NOT NULL COMMENT' Creation time ',
update_time DATETIME NOT NULL COMMENT' Update time ',
cover_image VARCHAR(255) COMMENT' Cover picture ',
PRIMARY KEY(blog_id),
CONSTRAINT FK_user_id FOREIGN KEY (userid) REFERENCES t_user(userId),-- Rename foreign keys
CONSTRAINT FK_type_id FOREIGN KEY (type_id) REFERENCES blog_type(type_id)
);
-- Blog comment form
CREATE TABLE t_comment
(
comment_id BIGINT NOT NULL AUTO_INCREMENT COMMENT' Comment on id',
comment_content VARCHAR(500) NOT NULL COMMENT' Comment content ',
blog_id BIGINT NOT NULL COMMENT' Comment content ',
createtime DATETIME NOT NULL COMMENT' Comment on time ',
userid BIGINT NOT NULL COMMENT' critics ID',
replyid INT NOT NULL COMMENT' Comment responder ID',
PRIMARY KEY(comment_id),
CONSTRAINT FK_comment_user_id FOREIGN KEY(userid) REFERENCES t_user(userId),
CONSTRAINT FK_comment_blog_id FOREIGN KEY(blog_id) REFERENCES t_blog(blog_id)
);
-- Create a blog tag table (t_tag), And establish the relationship between tables
CREATE TABLE t_tag
(
tag_id INT(11) NOT NULL AUTO_INCREMENT,
tag_name VARCHAR(32) NOT NULL,
PRIMARY KEY(tag_id)
);
/* Designed an intermediate table , It has a one to many relationship with blog information table and blog tag table respectively , So blog tag table (t_tag) Just like the blog information table (t_blog) It's a many to many relationship .*/
CREATE TABLE t_tag_blog
(
tag_id INT(11),
blog_id BIGINT(20),
FOREIGN KEY(tag_id) REFERENCES t_tag(tag_id),
FOREIGN KEY(blog_id) REFERENCES t_blog(blog_id)
);
4-13 Database query - Course selection system
USE School;
# Please add the implementation code here
########## Begin ##########
########## Insert student table (Student) Corresponding data ##########
insert into student(Sno,Sname,Ssex,Sage,Sdept)
values('9512101',' Li Yong ',' male ',19,' Department of Computer Science '),
('9512102',' Liu Chen ',' male ',20,' Department of Computer Science '),
('9512103',' Wang min. ',' Woman ',20,' Department of Computer Science '),
('9521101',' Zhang Li ',' male ',22,' Information Department '),
('9521102',' Wu Bin ',' Woman ',21,' Information Department '),
('9521103',' Zhang Hai ',' male ',20,' Information Department '),
('9531101',' Qian Xiaoping ',' Woman ',18,' Department of mathematics '),
('9531102',' Wang Dali ',' male ',19,' Department of mathematics ');
########## Insert course schedule (Course) Corresponding data ##########
insert into course(Cno,Cname,Ccredit,Semster,Period)
values('C01',' Computer culture ',3,1,41),
('C02','VB',2,3,61),
('C03',' computer network ',4,7,14),
('C04',' Database foundation ',6,6,24),
('C05',' Advanced mathematics ',8,2,19),
('C06',' data structure ',5,4,55);
########## Insert student course selection table (DBSC) Corresponding data ##########
insert into dbsc(ScID,Sno,Cno,Grade,isTec)
values(1,9512101,'c01',90,' Compulsory '),
(2,9512101,'c02',86,' Elective '),
(3,9512101,'c06',45,' Compulsory '),
(4,9512102,'c02',78,' Elective '),
(5,9512102,'c04',66,' Compulsory '),
(6,9521102,'c01',82,' Elective '),
(7,9521102,'c02',75,' Elective '),
(8,9521102,'c04',92,' Compulsory '),
(9,9521102,'c05',50,' Compulsory '),
(10,9521103,'c02',68,' Elective '),
(11,9521103,'c06',56,' Compulsory '),
(12,9531101,'c01',80,' Elective '),
(13,9531101,'c05',95,' Compulsory '),
(14,9531102,'c05',85,' Compulsory ');
########## End ##########
########## Query table data ##########
SELECT * FROM student;
SELECT * FROM course;
SELECT * FROM dbsc;
#********* Begin *********#
echo " select Sname,Sdept from student where Sdept=' Department of Computer Science '; select Sno from dbsc where Grade<60; select Sname,Sdept,Sage from student where Sage between 20 and 23 and Sdept=' Information Department '; select Sno,Grade from dbsc where Cno='c02' order by Grade desc; select count(*) from student; "
#********* End *********#
The first 3 Turn off : Refine Query
#********* Begin *********#
echo " select student.* from student where Sname like ' Zhang %'; select Sname,Ssex,Sdept from student where Sdept in (' Department of Computer Science ',' Information Department ',' Department of mathematics '); select Cno, count(*) from dbsc where isTec=' Elective ' group by Cno; select Sno from dbsc group by Sno Having count(*)>3; select Sname, Cno, Grade from student,dbsc where student.Sno=dbsc.Sno and Sdept=' Department of Computer Science '; "
#********* End *********#
Nor can we echo Add # notes
The first 4 Turn off : Complex queries
#********* Begin *********#
echo " select distinct student.Sno,student.Sname from dbsc,student where student.Sno=dbsc.Sno and isTec=' Elective '; select Sname,count(*),avg(Grade) from dbsc,student where student.Sno=dbsc.Sno group by dbsc.Sno Having avg(Grade); select avg(Grade),count(*) from dbsc group by Sno having count(*)>=4; select student.Sname, dbsc.Cno, dbsc.Grade from student left join dbsc on student.Sno=dbsc.Sno where student.Sdept=' Information Department ' and dbsc.isTec=' Elective ' and Cno='C02'; update dbsc set Grade = Grade+5 where Grade<60; "
#********* End *********#
边栏推荐
- Django running error: error loading mysqldb module solution
- Picture coloring project - deoldify
- Reading BMP file with C language
- [Blue Bridge Cup 2017 preliminary] grid division
- 【CDH】CDH/CDP 环境修改 cloudera manager默认端口7180
- QT creator custom build process
- nodejs连接Mysql
- [yarn] yarn container log cleaning
- Software I2C based on Hal Library
- Solution of deleting path variable by mistake
猜你喜欢
【yarn】Yarn container 日志清理
QT creator specify editor settings
解决安装Failed building wheel for pillow
MySQL与c语言连接(vs2019版)
Double to int precision loss
小L的试卷
Learn winpwn (2) -- GS protection from scratch
MTCNN人脸检测
error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_s instead
UDS learning notes on fault codes (0x19 and 0x14 services)
随机推荐
[NPUCTF2020]ReadlezPHP
【Flink】CDH/CDP Flink on Yarn 日志配置
QT creator custom build process
Word排版(小计)
天梯赛练习集题解LV1(all)
【flink】flink学习
QT creator runs the Valgrind tool on external applications
快来走进JVM吧
yarn安装与使用
error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_s instead
Solution of deleting path variable by mistake
Rhcsa certification exam exercise (configured on the first host)
SQL时间注入
One click extraction of tables in PDF
Julia 1.6 1.7 common problem solving
Face recognition_ recognition
Kept VRRP script, preemptive delay, VIP unicast details
Install mongdb tutorial and redis tutorial under Windows
Why can't I use the @test annotation after introducing JUnit
Aborted connection 1055898 to db: