当前位置:网站首页>Database day-4

Database day-4

2022-06-09 13:04:00 Right ear needs oil

Catalog

Daily test

Yesterday's review

constraint condition

  Foreign keys

Establish relationships between tables

Add

Modify table

Copy table

Summary of today's content

How to query a table

  Theory of connected table operation

Today's content is detailed

The execution order of several important keywords

where filter

group by grouping

Group notes

having Filter criteria after grouping

 distinct duplicate removal

order by Sort

limit Limit the number of displays

Regular

Multi meter operation

Preparation of the preliminary schedule

Table query

Subquery

summary

Homework


Daily test

  • What constraints do you know

  • There are several relationships between tables , How to determine

  • Create the above table relationship SQL Grammar how to write

Yesterday's review

constraint condition

"""
not null
zerofill
unsigned

default
    gender enum('male','female','others') default 'male'

unique
     It's unique
        id int unique
     Joint only
        ip int,
        port int,
        unique(ip,port)

primary key   Primary key
    1. Follow the restriction effect not null + unique Agreement
        id int primary key
    2. It's still Innodb Storage engine organizes data based on  
        1. Use Innodb Specify that a table must have only one primary key
        2. When you do not set the primary key
            1. Search from top to bottom for non empty and unique keys that are automatically promoted to primary keys
            2. If nothing is set Then the hidden fields will be used as the primary key
                 Can't use
            3. There should always be one in a table id Field and this field should be the primary key

auto_increment
     On the column
     This restriction can only be applied to fields that are set as keys And it is generally used together with the primary key
    id int primary key auto_increment
"""

Add knowledge points for the primary key
     When you delete the data in the table The primary key autoincrement does not stop  
  
truncate Clear the data and reset the primary key

  Foreign keys

"""
 Foreign keys are used to truly implement the relationship between tables at the code level 
foreign key
"""

Establish relationships between tables

"""
 There are only three relationships with tables 
	 One to many 
		 stay MySQL in   One to many and many to one   It's called one to many 
         The foreign key field is built on the side with more 
	 Many to many 
		 Relationships do not require foreign keys   Instead, a separate table is created to store relationships 
	 one-on-one 
		 Foreign key fields can be built on either side 
		 But it is recommended that you build in the table with high query frequency 
"""
""" If you are not proficient in judging the relationship between tables in the early stage, you must think in another position   Ask yourself slowly """

#  One to many judgment 
 Books and publishers 
	 First stand in the book table 
    	 Whether a book can be published by multiple publishers 			 Copyright issues   Can not be !!!
     Then stand in the press table 
    	 Can a publishing house publish more than one book 			 Sure 
     Conclusion : One way one to many is true   So the table relation is one to many    Books are one of many 
    
 Constraints imposed by foreign keys 
	1. When creating a table, you must first create the associated table 
    2. When inserting data, you should also insert the associated table first 
    3. When operating data   There are many restrictions    Synchronize updates   Sync delete 
   	create table publish(
    	id ...
    );
    create table book(
    	id ...
        publish_id int,
        foreign key(publish_id) references publish(id)
        on update cascade  #  Synchronize updates 
        on delete cascade  #  Sync delete 
    );
    
#  Many to many 
	 Books and authors 
    	 First stand in the book table 
        	 Can a book have more than one author 	 Sure !!!
         Then stand on the author table 
        	 Can an author write more than one book 		  Sure !!!
    	 Conclusion : Books and authors are two-way, one to many   So the table relation is   Many to many 
        
         Be sure to create a new table to store table relationships 
    create table book(
    	id ...
    )
    create table author(
    	id ...
    )
    create table book2author(
    	id ...
        book_id int,
        author_id int,
        foreign key(book_id) references book(id)
        on update cascade  #  Synchronize updates 
        on delete cascade,  #  Sync delete 
        foreign key(author_id) references author(id)
        on update cascade  #  Synchronize updates 
        on delete cascade,  #  Sync delete 
    )
#  one-on-one 
	qq User table 
     Customer and student table 
    """
    	 When the data in a table is not all the data required by frequency   But there are so many fields 
    	 At this time, you should consider dividing the tables   Then do a one-to-one correlation 
    	 Save query time and transmission time 
    """
     Author and author details 
    	 No matter which side you stand on, one to many cannot be established 
         Neither one to many relationship is established 
        	 one-on-one 
             It doesn't matter. 
    create table author(
    	id ...
        authordetail_id int unique,
        foreign key(authordetail_id) references authordetail(id)
        on update cascade  #  Synchronize updates 
        on delete cascade,  #  Sync delete 
    );
    create tabel authordetail(
    	id ...
    );

Add

"""
 If there is a relationship between tables   There are two ways to make a connection 
	1. Is to establish a relationship through foreign keys 
	
	2. Is to pass sql Build relationships at the logical level of statements 
		delete from emp where id=1;
		delete from dep where id=1;
	
	 Creating a foreign key consumes a certain amount of resources   And the coupling between tables is increased 
	 In the actual project   If there are too many watches   In fact, you can not do any foreign key processing   direct 
	 adopt sql Statement to establish a logical relationship 
	 Whether foreign keys are used or not depends on the actual project requirements 
"""

Modify table

"""
alter table t1 rename new_t1;

alter table t1 add  Field name  ...;
alter table t1 add  Field name  ... first;
alter table t1 add  Field name  ... after  Old fields ;

alter table t1 drop  Field name ;

modify Generally, it is used to modify the field type   Constraints, etc   Field name cannot be modified 
alter table t1 modify  Field name   data type ( Width )  constraint condition 

alter table t1 change  Old field name   new field name  ...;
"""

Copy table

"""
 We sql The result of the statement query can also be regarded as a table ( Virtual table )
 Between the lines   For this query result, you can continue to operate the virtual table with the syntax of the query table 
"""

Summary of today's content

How to query a table

"""
select
where 
group by
having
distinct
order by
limit 
regexp
like
...
"""

  Theory of connected table operation

Today's content is detailed

Preparation of the preliminary schedule

create table emp(
  id int not null unique auto_increment,
  name varchar(20) not null,
  sex enum('male','female') not null default 'male', # Most of them are men 
  age int(3) unsigned not null default 28,
  hire_date date not null,
  post varchar(50),
  post_comment varchar(100),
  salary double(15,2),
  office int, # One department, one room 
  depart_id int
);

# insert record 
# Three departments : teaching , sales , operating 
insert into emp(name,sex,age,hire_date,post,salary,office,depart_id) values
('jason','male',18,'20170301',' The first handsome image of Zhangjiang ',7300.33,401,1), # Here is the teaching department 
('tom','male',78,'20150302','teacher',1000000.31,401,1),
('kevin','male',81,'20130305','teacher',8300,401,1),
('tony','male',73,'20140701','teacher',3500,401,1),
('owen','male',28,'20121101','teacher',2100,401,1),
('jack','female',18,'20110211','teacher',9000,401,1),
('jenny','male',18,'19000301','teacher',30000,401,1),
('sank','male',48,'20101111','teacher',10000,401,1),
(' ha-ha ','female',48,'20150311','sale',3000.13,402,2),# Here is the sales department 
(' ha-ha ','female',38,'20101101','sale',2000.35,402,2),
(' West ','female',18,'20110312','sale',1000.37,402,2),
(' Lele ','female',18,'20160513','sale',3000.29,402,2),
(' Lala ','female',28,'20170127','sale',4000.33,402,2),
(' Seng long ','male',28,'20160311','operation',10000.13,403,3), # Here's the operations department 
(' Cheng Yaojin ','male',18,'19970312','operation',20000,403,3),
(' Cheng Yaoyin ','female',18,'20130311','operation',19000,403,3),
(' Cheng Yaotong ','male',18,'20150411','operation',18000,403,3),
(' Cheng yaotie ','female',18,'20140512','operation',17000,403,3);


#  When there are many table fields   The display was disorderly   have access to \G Branch display 
select * from emp\G;

#  Individual students' computers will still appear garbled or blank when inserting Chinese   You can set the character encoding to GBK

The execution order of several important keywords

#  Writing order 
select id,name from emp where id > 3;
#  Execution order 
from
where
select

"""
 Although the execution order is inconsistent with the writing order   You're writing sql You may not know how to write a statement 
 You just write in writing order sql
	select *  First use * No. occupation 
	 Then go and complete the back sql sentence 
	 The final will be * The specific field you want after number replacement 
	
	 It will be used all the time tomorrow   Let's first understand 
"""

where filter

#  effect : It is a filtering operation for the overall data 
# 1. Inquire about id Greater than or equal to 3 Less than or equal to 6 The data of 
select id,name,age from emp where id>=3 and id<=6;
select id,name from emp where id between 3 and 6;   The two are equivalent 

# 2. Query salary is 20000 perhaps 18000 perhaps 17000 The data of 
select * from emp where salary=20000 or salary=18000 or salary=17000;
select * from emp where salary in (20000,18000,17000);

# 3. The query employee name contains letters o The name and salary of the employee 
"""
 Fuzzy query 
	like
		%   Match any number of characters 
		_   Match any single character 
"""
select name,salary from emp where name like '%o%';

# 4. The query employee name is composed of four characters   Name and salary   char_length()   _
select name,salary from emp where name like '____';
select name,salary from emp where char_length(name) = 4;

# 5. Inquire about id Less than 3 perhaps id Greater than 6 The data of 
select * from emp where id not between 3 and 6;

# 6. Query salary is not in 20000,18000,17000 Range data 
select * from emp where salary not in (20000,18000,17000);

# 7. Query the employee name and position name with empty position description    in the light of null No equal sign   use is
select name,post from emp where post_comment = NULL;
select name,post from emp where post_comment is NULL;

group by grouping

#  Group actual application scenarios    There are many grouping application scenarios 
	 The male to female ratio 
     Average departmental salary 
     Department baldness rate 
     Statistics between countries 

# 1	 Group by Department 
select * from emp group by post;
"""
 After grouping   The smallest operational unit should be group   It's no longer a single data in a group 
	 The above commands can be executed normally when you do not set strict mode   What is returned is after grouping   The first data in each group   But this does not meet the grouping specification : Individual data should not be considered after grouping   Instead, it should take the group as the operation unit ( After grouping   There is no way to directly obtain individual data in the group )
	 If strict mode is set   Then the above command will directly report an error  
"""
set global sql_mode = 'strict_trans_tables,only_full_group_by';

 After setting strict mode    grouping   By default, you can only get the grouping basis 
select post from emp group by post;  
 According to what group, you can only get the group   Other fields cannot be obtained directly   Some methods are needed ( Aggregate functions )


"""
 When do you need to group ???
	 keyword  
		 Every   Average   The highest   The minimum  
	
	 Aggregate functions 
		max
		min
		sum
		count
		avg
"""
# 1. Get the highest salary for each department 
select post,max(salary) from emp group by post;
select post as ' department ',max(salary) as ' The highest salary ' from emp group by post;
select post ' department ',max(salary) ' The highest salary ' from emp group by post;
# as You can alias fields   You can also omit it directly   But not recommended   Because the meaning of omitted words is not clear   It's easy to get confused 

# 2. Get the minimum wage for each department 
select post,min(salary) from emp group by post;
# 3. Get the average salary for each department 
select post,avg(salary) from emp group by post;
# 4. Get the total salary of each department 
select post,sum(salary) from emp group by post;
# 5. Get the number of people in each department 
select post,count(id) from emp group by post;  #  Commonly used   It's logical 
select post,count(salary) from emp group by post;
select post,count(age) from emp group by post;
select post,count(post_comment) from emp group by post;  null no way 

# 6. Query the name of the Department after grouping and the names of all employees in each department  
# group_concat It can not only support you to obtain other field values after grouping   It also supports splicing operation 
select post,group_concat(name) from emp group by post;
select post,group_concat(name,'_DSB') from emp group by post;
select post,group_concat(name,':',salary) from emp group by post;
# concat When not grouped, use  
select concat('NAME:',name),concat('SAL:',salary) from emp;

#  Add  as Syntax doesn't just alias fields   You can also temporarily alias the table 
select emp.id,emp.name from emp;  
select emp.id,emp.name from emp as t1;    Report errors 
select t1.id,t1.name from emp as t1;

#  Check everyone's annual salary   12 pay 
select name,salary*12 from emp;

Group notes

#  keyword where and group by At the same time group by Must be in where Behind 
where Filter the overall data before grouping 
where Filter criteria cannot use aggregate functions 
select id,name,age from emp where max(salary) > 3000;

select max(salary) from emp;  #  Not in groups   The default whole is a set of 

#  The age of each department is in 30 Average salary of employees over years old 
	1  Let's ask all people older than 30 Year old employees 
    	select * from emp where age>30;
    2  Then group the results ( By Department )
     	select * from emp where age>30 group by post;
    
    select post,avg(salary) from emp where age>30 group by post;

having Filter criteria after grouping

"""
having The grammatical root of where It's consistent 
 It's just having It is the filtering operation after grouping 
 namely having Aggregate functions can be used directly 
"""
#  The age of each department is in 30 The average salary of employees over years old and keep the average salary greater than 10000 The department in charge of the 
select post,avg(salary) from emp 
		where age>30 
    	group by post
        having avg(salary) > 10000
        ;

 distinct duplicate removal

"""
 Be sure to pay attention to   The data must be exactly the same before it can be de duplicated !!!
 Be sure not to neglect   There are cases of gradual existence   It's impossible to go heavy 
[
{'id':1,'name':'jason','age':18},
{'id':2,'name':'jason','age':18},
{'id':3,'name':'egon','age':18}
]
ORM   Object relation mapping     Don't understand SQL Statement can also be very powerful to operate the database 
 surface 								 class 
 Pieces of data 						 object 
 The value corresponding to the field 						 Object properties 

 You write class again   That means creating tables 
 Generate objects with classes   That means re creating data 
 Object point properties   Is to get the value corresponding to the data field 
 The purpose is to reduce python The pressure of programmers   Just need to be able to python Object oriented knowledge points can be operated MySQL
"""
select distinct id,age from emp;
select distinct age from emp;

order by Sort

select * from emp order by salary;
select * from emp order by salary asc;
select * from emp order by salary desc;
"""
order by The default is ascending   asc  The asc You can omit it 
 You can also change it to descending      desc
"""
select * from emp order by age desc,salary asc;
#  First according to age Descending order    If you come across age identical   Then follow salary Ascending row 

#  The age of each department is in 10 The average salary of employees over years old and keep the average salary greater than 1000 The department in charge of the , And then sort the average wage in descending order 
	select post,avg(salary) from emp 
		where age>10 
    	group by post
        having avg(salary) > 1000
        order by avg(salary) desc
        ;

limit Limit the number of displays

select * from emp;
""" In case of too much data   We usually do paging """
select * from emp limit 3;  #  Show only three pieces of data 

select * from emp limit 0,5;
select * from emp limit 5,5;
 The first parameter is the starting position 
 The second parameter is the number of display entries 

Regular

select * from emp where name regexp '^j.*(n|y)$';

Multi meter operation

Preparation of the preliminary schedule

# Build table 
create table dep(
id int,
name varchar(20) 
);

create table emp(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);

# insert data 
insert into dep values
(200,' technology '),
(201,' human resources '),
(202,' sales '),
(203,' operating ');

insert into emp(name,sex,age,dep_id) values
('jason','male',18,200),
('egon','female',48,201),
('kevin','male',18,201),
('nick','male',28,202),
('owen','male',18,203),
('jerry','female',18,204);

Table query

select * from dep,emp;  #  result     The cartesian product 
"""
 Understanding can   It doesn't matter if I don't know 
"""

select * from emp,dep where emp.dep_id = dep.id;

"""
MySQL I know   When you query the data later   I'm sure you'll often use the spelling operation  
 So I specially set up corresponding methods for you 
	inner join   Internal connection 
	left join    Left connection 
	right join   The right connection 
	union		 Full connection 
"""
# inner join   Internal connection 
select * from emp inner join dep on emp.dep_id = dep.id;
#  Splice only the public data parts of the two tables 

# left join    Left connection 
select * from emp left join dep on emp.dep_id = dep.id;
#  All the data in the left table are displayed   If there is no corresponding item, use NULL

# right join   The right connection 
select * from emp right join dep on emp.dep_id = dep.id;
#  All the data in the right table are displayed   If there is no corresponding item, use NULL

# union		 Full connection    All the data in the left and right tables are displayed 
select * from emp left join dep on emp.dep_id = dep.id
union
select * from emp right join dep on emp.dep_id = dep.id;

Subquery

"""
 Subquery is the way we usually solve problems 
	 Solve the problem step by step 
		 First step 
		 The second step 
		...
 Use the result of one query statement as the condition of another query statement 
"""
#  Query the employee information of technical or human resources department 
	1  First get the Department's id Number 
    2  Then go to the employee table to select the corresponding employees 
    select id from dep where name=' technology ' or name = ' human resources ';
    
    select name from emp where dep_id in (200,201);
    
    
    select * from emp where dep_id in (select id from dep where name=' technology ' or name = ' human resources ');

summary

 Table query results can be used as query criteria for other tables 
 You can also alias it as a virtual table root and associate it with other tables 

"""
 There are two ways to query multiple tables 
	 Splice the table first and then query 
	 Subquery   Step by step 
"""

Homework

1. Organize today's content 
2. Complete the following group query exercises ( Take the table building code in class as a reference )
	1.  Query the position name and all employee names included in the position 
	2.  Query the position name and the number of employees in each position 
	3.  Check the number of male and female employees in the company 
	4.  Query position name and average salary of each position 
	5.  Query position name and maximum salary of each position 
	6.  Query position name and minimum salary of each position 
	7.  Query the average salary of male employees and male employees , The average salary of female employees and female employees 
3. Practice spelling and understand its meaning 
4. Understand the idea of subquery and realize its significance 

原网站

版权声明
本文为[Right ear needs oil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091209019138.html