当前位置:网站首页>Day 47 how to query a table
Day 47 how to query a table
2022-06-11 09:18:00 【lwj_ 07】
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
Be careful :
"""
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
"""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 (count You can count any field in the following table except null Outside )
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; Report errors
select max(salary) from emp; # Not in groups Default overall (emp) It's a group
# 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
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; # From the first to the fifth
select * from emp limit 5,5; # Start with the sixth and take five more
The first parameter is the starting position
The second parameter is the number of display entries Regular ( Understanding can )
select * from emp where name regexp '^j.*(n|y)$';
^j : Express j start
(n|y)$ : Express n or y ending
In the middle 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 ( Commonly used )
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
1 Splice the table first and then query
2 Subquery Step by step
"""边栏推荐
- openstack详解(二十一)——Neutron组件安装与配置
- 1400. construct K palindrome strings
- 1721. exchange nodes in the linked list
- [C language - data storage] how is data stored in memory?
- Interview question 02.02 Return the penultimate node
- Shandong University project training (IV) -- wechat applet scans web QR code to realize web login
- Why is it difficult to implement informatization in manufacturing industry?
- kubelet Error getting node 问题求助
- 报错[DetectionNetwork(1)][warning]Network compiled for 6 shaves,maximum available 10,compiling for 5 s
- 682. baseball game
猜你喜欢

机器学习笔记 - 使用TensorFlow的Spatial Transformer网络

Type-C Bluetooth speaker single port rechargeable OTG solution

报错RuntimeError: BlobReader error: The version of imported blob doesn‘t match graph_transformer

PD chip ga670-10 for OTG while charging

Runtimeerror: blobreader error:the version of imported blob doesn't match graph_ transformer
![Error [detectionnetwork (1)][warning]network compiled for 6 shapes, maximum available 10, compiling for 5 S](/img/54/f42146ae649836fe7070ac90f2160e.png)
Error [detectionnetwork (1)][warning]network compiled for 6 shapes, maximum available 10, compiling for 5 S

Openstack explanation (XXIII) -- other configurations, database initialization and service startup of neutron

MSF SMB based information collection

Install jupyter in the specified environment

Machine learning notes - in depth Learning Skills Checklist
随机推荐
Comparison and introduction of OpenCV oak cameras
Modularnotfounderror: no module named 'find_ version’
市场上的服装ERP体系到底是哪些类型?
Award winning survey streamnational sponsored 2022 Apache pulsar user questionnaire
shell脚本之sed详解 (sed命令 , sed -e , sed s/ new / old / ... )
[C language - data storage] how is data stored in memory?
openstack详解(二十一)——Neutron组件安装与配置
Why is it difficult to implement informatization in manufacturing industry?
OpenCV CEO教你用OAK(五):基于OAK-D和DepthAI的反欺骗人脸识别系统
Install jupyter in the specified environment
Talk about reading the source code
CUMT学习日记——ucosII理论解析—任哲版教材
考研數學 【數列極限證明題】題型方法總結
86. separate linked list
1493. the longest subarray with all 1 after deleting an element
1400. 构造 K 个回文字符串
How win10 Home Edition connects to remote desktop
报错ModularNotFoundError: No module named ‘find_version’
矩阵求逆操作的复杂度分析(逆矩阵的复杂度分析)
When the enterprise makes a decision, which part should lead the ERP project?