Happy to take you to learn MySQL database Part 7

previewfile_2967697841

Constraints provided by MySQL
1.not null
2.unique
3.default
4.primary key
5.foreign key

table design

  1. find entity
  2. Determine relationships between entities
    • One to one
    • one to many
    • many to many

Aggregation query
~~Operations between rows
~~Aggregation function
~~Group by

Union query

~~Multi-table query
~~Cartesian product: put two tables together to arrange and combine

class schedule

classId className
1 Class 1
2 Class 2

Student table

studentId name classId
1 Zhang San 1
2 John Doe 1
3 Wang Wu 2
4 Zhao Liu 2

Cartesian product result of student table and class table

studentId name classId classId className
1 Zhang San 1 1 Class 1
1 Zhang San 1 2 Class 2
2 John Doe 1 1 Class 1
2 John Doe 1 2 Class 2
3 Wang Wu 2 1 Class 1
3 Wang Wu 2 2 Class 2
4 Zhao Liu 2 1 Class 1
4 Zhao Liu 2 2 Class 2

The Cartesian product results in a larger table.
The number of columns in the Cartesian product is the sum of the column numbers of the two tables.
The number of rows is the product of the row numbers of the two tables.

Since the Cartesian product is the result of permutation and combination, some of the data here are invalid/meaningless data.

image-20230909004649269

After removing the invalid data, the remaining data in the Cartesian product is the information about which class each student is currently in.

studentId name classId classId className
1 Zhang San 1 1 Class 1
2 John Doe 1 1 Class 1
3 Wang Wu 2 2 Class 2
4 Zhao Liu 2 2 Class 2

For example, "two classlds match" can be described in SQL using a where clause condition
to query based on Cartesian product + condition. This is a joint query/multi-table query.

drop table if exists classes;
drop table if exists student;
drop table if exists course;
drop table if exists score;

create table classes(
    id int primary key auto_increment, 
    name varchar(20), 
   `desc` varchar(100)
);
create table student(
    id int primary key auto_increment,
    sn varchar(20), 
    name varchar(20),
    qq_mail varchar(20), 
    classes_id int
);
create table course(
    id int primary key auto_increment, 
    name varchar(20)
);
create table score(
    score decimal(3,1), 
    student_id int, course_id int
);

insert into classes(name, `desc`) values  
	('计算机系2019级1班 ', '学习了计算机原理、C和Java语言、数据结构和算法 '), 	         ('中文系2019级3班 ','学习了中国传统文学 '), 
    ('自动化2019级5班 ','学习了机械自动化 ');
    
insert into student(sn, name, qq_mail, classes_id) values 
    ('09982','黑旋风李逵 ','[email protected]',1), 
    ('00835','菩提老祖 ',null,1), 
    ('00391','白素贞',null,1), 
    ('00031','许仙 ','[email protected]',1), 
    ('00054','不想毕业 ',null,1), 
    ('51234','好好说话 ','[email protected]',2), 
    ('83223','tellme',null,2),
    ('09527','老外学中文 ','[email protected]',2); 
    
insert into course(name) values 
    ('Java'),('中国传统文化 '),('计算机原理 '),('语文 '),('高阶数学 '),('英文 '); 
    
insert into score(score, student_id, course_id) values 
-- 黑旋风李逵 
	(70.5, 1, 1),(98.5, 1, 3),(33, 1, 5),(98, 1, 6), 
-- 菩提老祖 
    (60, 2, 1),(59.5, 2, 5), 
-- 白素贞 
    (33, 3, 1),(68, 3, 3),(99, 3, 5), 
-- 许仙 
    (67, 4, 1),(23, 4, 3),(56, 4, 5),(72, 4, 6), 
-- 不想毕业 
    (81, 5, 1),(37, 5, 5), 
-- 好好说话 
    (56, 6, 2),(43, 6, 4),(79, 6, 6), 
-- tellme 
    (80, 7, 2),(92, 7, 6); 

image-20230909095954018

(1) Query the score of classmate ''Xu Xian''
"Xu Xian" => student table
score => score table
~~ The two key information you are looking for exist in different tables, so you need to perform a joint query
1) First Cartesian product of student table and score table => select * from student, score;
2) Remove invalid data => select * from student, score where id = student_id;
3) Filter according to the name "Xu Xian" =>select * from student, score where id = student_id and student.name = '许仙';

image-20230909102622273

The number of rows in the current result is already what we requested. We also need to streamline the number of columns~~
select student.name, score.score from student, score where id = student_id and student.name = '许仙';
image-20230909103039670

What should I do if the column names have the same name?
Specify the column by table name and column name
⭐️⭐️⭐️ It is recommended that you explicitly write out the table name when querying multiple tables.
select * from student, score where student.id = score.student_id;

General implementation steps for multi-table queries:
1. Analyze clearly in which tables the information involved in the requirements is located
2. Perform Cartesian product on these multiple tables.
3. Filter out the valid data (here, use student ID as Associated conditions)
4. Combine the conditions in the requirements to further strengthen the conditions
5. Streamline the columns

Multi-table query Another way to query the grades of classmate ''Xu Xian''
1) Complete the Cartesian product => select * from student join score;
2) At this time, the subsequent conditions do not use the where keyword, but use on
~~ select * from student join score on student.id = score.student_id;
3) Filter by name select * from student join score on student.id = score.student_id and student.name = '许仙';
4) Streamline columns select student.name, score.score from student join score on student.id = score.student_id and student.name = '许仙';
image-20230909105339762

The effect of using join on is the same as the first method.

(2) Query the total scores of all students and their personal information.
Total score => score table/score table.
Personal information => student table/student table.
At this time, you need to group by the student name/student number and then target For each group, sum separately

select 
	student.name, 
	sum(score.score) 
from 
	student, 
	score where student.id = score.student_id 
group by 
	id;

image-20230909114624852

Union query must be the last big question when taking the database class exam in school. In
actual development, use union query carefully~~Joint query is essentially a "Cartesian product". The Cartesian product arranges multiple tables. Combination...
If there is a lot of data in the table, the Cartesian product overhead is very large!!

(3) Query the grades, course names, and classmate names of all students.
Student name => student table
, course name => course table, score => score table => three tables
related to the student and course tables , you need to specify two.
Connection conditions

select 
	student.name, 
	course.name, 
	score.score 
from 
	student, 
	course, score 
where 
	student.id = score.student_id 
and 
	course.id = score.course_id;

Most of the interview questions are actually clear and unambiguous and are not memorized by rote.
Time complexity of binary search tree query => O(N)
time complexity of hash table query => O(1)
default It is the worst, not the average!!! A single tree is equivalent to a linked list. It must
be a balanced binary search tree to achieve logN~~TreeMap has a red-black tree

One of the most important principles in interviews is to seek truth from facts!!!
Never make it up if you don’t know it. Interviewers have read countless people~~ People can easily tell whether you are making it up~If you are exposed, you are a complete clown!! !


outer join

The above joint queries are actually "inner joins".
MySQL also has a joint query called an outer join. Both
inner joins and outer joins perform Cartesian products. But there are differences in details.

create table student(
	id int,
	name varchar(20)
);
create table score(
    student_id int, 
    score int
);
insert into student values
	(1, '张三'),
	(2, '李四'),
	(3, '王五');
insert into score values
	(1, 90),
	(2, 80),
	(3, 70);

Under the current situation, the data in these two tables are in one-to-one correspondence (each record in the first table is reflected in the second table. Each record in the second table is reflected in the first table. Both are reflected) At this time, the query results of inner connection and outer connection are the same.
Inner connection

select 
	name, 
	score 
from 
	student join score 
on 
	student.id = score.student_id;

Outer joins are divided into left outer joins and right outer joins. If the joint query is performed, if the table on the left is completely displayed, it is called a left outer join; if the table on the right is completely displayed, it is called a right outer join. Left
outer
join

-- 左外连接,表1完全显示
select 字段名 from 表名1 left join 表名2 on 连接条件;

select 
	name, 
	score 
from 
	student left join score 
on 
	student.id = score.student_id;

right outer join

-- 右外连接,表2完全显示
select 字段 from 表名1 right join 表名2 on 连接条件;

select 
	name, score 
from 
	student right join score 
on 
	student.id = score.student_id;

If the data in the two tables no longer correspond one to one, and an inner join is performed at this time, the result will be only the data reflected in both tables.
If a left outer join is performed, the table on the left will prevail. In the table on the left All the data in the table can be reflected.
If you perform a right outer join, the table on the right will prevail. All the data in the table on the right will be reflected.

image-20230909151820417

In contrast, inner joins are used more often. Outer joins are mainly used in some specific scenarios.
How to perform outer join queries for joint queries of three tables?
Join on can also be performed on multiple tables~~select * from table 1 join table 2 on condition 1 join table 3 on condition 2

Three tables => left table, middle table, right table.
First consider the left table and the middle table for outer join. Get a "temporary" table,
then use this "temporary" table and the right table for outer join
select * from table 1 [left /right] join table 2 on condition 1 [left/right] join table 3 on condition 2

self-connection

~~ Strange tricks, special operations under special circumstances, not general usage. If you understand it, you can
connect with yourself => Do Cartesian product with yourself => This operation is essentially to convert "rows" into "columns" "
~~ Conditional queries in SQL all specify a certain column/multiple columns to perform relational operations, and
cannot perform relational operations between rows. Sometimes in order to achieve this comparison between rows, it is necessary to compare rows The relationship is converted into a column relationship.
Example: Display the score information of all "Computer Principles" with higher scores than "Java".
"Computer Principles", "Java" => in the course table,
grade information => in the score table
. Self-joining needs to specify the alias of the table.

select 
	* 
from 
	score as s1, 
	score as s2 
where 
	s1.student_id = s2.student_id 
	and s1.course_id = 1 
	and s2.course_id = 3 
	and s1.score < s2.score;

The logical expression ability of SQL is limited. In many cases, it is not that it cannot be done, but the cost is high. In contrast, using a language like Java to describe complex logic is a better choice!!

subquery

Two words~~Matryoshka => Merge multiple query statements into one
~~Once the subqueries are nested at too many levels, it will be a devastating blow to the readability of the code!
Subqueries are used in actual development Be careful when doing it!!!

Single-row subquery: A subquery that returns one row of records.
Query the classmates of "do not want to graduate" students.

-- 第一步
select 
	classes_id 
from 
	student 
where = '不想毕业';
-- 第二步
select 
	name 
from 
	student 
where class_id = 1;

-- 上面两步查询等效于下面的一步查询
select 
	name 
from 
	student 
where 
	classes_id = (select classes_id from student where name = '不想毕业');

Multi-row subquery: A subquery that returns multiple rows of records
to query the score information of "Chinese" or "English" courses

-- 第一步
select 
	id 
from 
	course 
where name = '语文' or name = '英文';
-- 第二步
select 
	* 
from 
	score 
where 
	course_id in (4, 6);
-- 上面两步查询等效于下面的一步查询
select 
	* 
from 
	score 
where 
	course_id in 
	(select id from course where name = '语文' or name = '英文');
merge query

Merge the results of the two query statements together using
the union keyword
~~ In advanced C, the custom type is explained in detail.
struct => structure
union => union => Essentially, it is to allow data in a memory to have Multiple ways of understanding~ Just like a person, there are many identities with the same identity. Is
there a union in java? Why is there no union in java??~~
~~ Times have changed!!! The programming environment that C faced back then It is relatively backward~~ The hardware resources provided by computers are very limited!!! The memory is only a few kb, so the space must be utilized to the extreme~~ Later, computers advanced by leaps and bounds, and at this time, the memory was no longer valuable => union is useless Takechiro's
childhood games include the Subtitles/Famicom games Contra and Super Mario. A game space is about 64kb, and the larger one is 128kb. In the 64kb space, there are many levels, many characters, and many npc, many maps, many props, as well as animation effects, audio effects, various plots... What’s even more frightening is that there are also 3D games~~ => The utilization of memory space has reached a shocking level, and the development of those years Programmers of FC games are all great!!!
Case: Query courses with ID less than 3 or with the name "English"

select * from course where id < 3 or name = '英文';
-- 与下面的SQL语句等效
select * from course where id < 3 
union 
select * from course where name = '英文';

Note: or can only target one table, while union can combine the query results of multiple tables (requiring multiple results to be listed correspondingly), which has a wider scope of application and is stronger than or; union will automatically remove duplicates, union
all Will not remove weight

Guess you like

Origin blog.csdn.net/m0_73740682/article/details/132780483