当前位置:网站首页>Introduction to MySQL (II) sub query + Association
Introduction to MySQL (II) sub query + Association
2022-06-23 05:23:00 【The silent Lord returns to the sand】
- Relational query ( a key )
1.1 Subquery
summary : The result of one query is used as the condition of another query
grammar :SELECT Name FROM Table name Where Conditions ( Subquery results )
Case study : Query salary greater than Bruce Employee information
1. First find out Bruce The salary of ( Line by line )
select salary from t_employees where first_name='Bruce';
2. Query salary greater than Bruce Employee information
SELECT * FROM t_employees where salary>6000;
3. Combine ( Subquery )
SELECT * FROM t_employees where salary>(select salary from t_employees where first_name='Bruce');
Subquery ----------- Multiple rows and single column
SELECT Name FROM Table name Where Name in ( Subquery results );
Case study 1: Query with name ’King’ Employee information of the same department
- First query ‘King’ Department No ( Multi row single row )
select department_id from t_employees where last_name='King';
- The query again 80、90 Employee information of department No
select * from t_employees where department_id in (80,90);
- Combine
select * from t_employees where department_id in (select department_id from t_employees where last_name='King');
Case study 2: Pay more than 60 Information about the Department owner
1. Inquire about 60 The salary of the Department owner ( Multi row single row )
select salary from t_employees where department_id=60;
2. The query is higher than 60 Employee information about the salary of the Department owner ( Above all )
select * from t_employees where salary > all(select salary from t_employees where department_id=60);
The query is higher than 60 Employee information about the salary of the Department ( The higher part )
select * from t_employees where salary > any(select salary from t_employees where department_id=60);
[ Be careful : When the subquery result set is in the form of multiple rows and single columns, you can use ANY or ALL keyword ]
Subquery ---------- As a table
grammar :SELECT Name FROM( The result set of the subquery ) WHERE Conditions ;
Case study : Query the top salary in the employee table 5 Employee information of name
- Sort the salaries of all employees first ( Sorted temporary table )
select * from t_employees ORDER BY salary DESC;
- Then query the first... In the temporary table 5 Line employee information
select * from t_employees LIMIT 0,5;
Combine :
select * from (select * from t_employees ORDER BY salary DESC) as emp LIMIT 0,5;
Be careful : You need to alias the virtual table of the result set
Direct splicing of two conditions :
select * from t_employees ORDER BY salary DESC LIMIT 0,5;
1.2 Merge query – The two tables are put together ( understand )
SELECT * FROM Table name 1 UNION SELECT * FROM Table name 2 ---- Remove duplication
SELECT * FROM Table name 1 UNION ALL SELECT * FROM Table name 2 ---- No duplication is removed
select * from t1 UNION SELECT * from t2;
select * from t1 UNION ALL select * from t2;
Application scenarios : Use less , Generally, it is only used in specific scenes , for example : Merge two class tables ;( The fields are consistent )
1.3 Link query
Internal connection ---- The matching records in the two tables will be queried ( a key )
SELECT Name FROM surface 1 How to connect surface 2 ON Connection condition
Case study : Query the matching records in the teacher table and the class table
sql Standard way : inner join on
select t.id,t.name,c.name as classname from teacher t inner JOIN classes c on t.id=c.t_id;
mysql The way
select * from teacher t,classes c where t.id=c.t_id;
External connection ---- Left outer and right outer LEFT JOIN RIGHT JOIN
Left lateral : Take the table on the left , All have to be displayed , There is no match on the right , Is displayed null
Right outside : Take the table on the right , All have to be displayed , There is no match on the left , Is displayed null
SELECT * FROM teacher t LEFT JOIN classes c ON t.id=c.t_id;
SELECT * FROM teacher t RIGHT JOIN classes c ON t.id=c.t_id;
- DML operation ( Additions and deletions )( a key )
add to : INSERT INTO Table name ( Column 1, Column 2, Column 3…) VALUES( value 1, value 2, value 3…);
Add a job information
select * from t_jobs;
insert into t_jobs(job_id,job_title,min_salary,max_salary) values('QF_GP','QF_1',16000,26000);
modify :UPDATE Table name SET Column 1= The new value 1 , Column 2 = The new value 2,…WHERE Conditions ;
Case study 1: The revision number is 100 The salary of our employees is 25000
update t_employees set salary=25000 WHERE employee_id=100;
Be careful : If not where, All records in the table will be modified
Case study 2: The revision number is 135 The position number of the employee information is ST_MAN, The salary is 3500
update t_employees SET job_id='ST_MAN',salary=3500 where employee_id=135;
Delete : DELETE FROM Table name WHERE Conditions ;
Be careful : Delete also often add where Conditions , Otherwise, delete all records
Delete No 135 The employees'
delete from t_employees WHERE employee_id=135;
Delete last name Peter, And it's called Hall The employees'
delete FROM t_employees where first_name='Peter' and last_name='Hall';
Clear the whole table data (TRUNCATE)
TRUNCATE TABLE Table name ; — This deletion is more thorough , Will delete all tables , Then create an empty table
TRUNCATE table t1;
- data type
Used to constrain the type of stored value
Key types to remember : int double(5,2) date datetime char VARCHAR
3.1 Create table
create table student(
id int(4),
name VARCHAR(20)
);
3.2 Modification of data sheet
ALTER TABLE Table name operation ;
Add columns to an existing table
alter table student add age int;
Modify the column information in the table
alter table student MODIFY name VARCHAR(30);
Delete the columns in the table
alter table student drop age;
Change column names
alter table student CHANGE name st_name VARCHAR(20);
Modify the name of the table
alter table student rename t_student;
Delete data table
drop table student;
- constraint
problem : Create a table , Can I insert two identical pieces of data , If possible , What are the disadvantages
disadvantages : Unable to determine a unique record
Entity integrity constraints ==
4.1 Primary key constraint
The unique identification of a record , Often set to id in , Not for null
create table student(
id int(4) primary KEY,
name VARCHAR(20)
);
INSERT INTO student(id,name) values(1,' Zhang San ');
INSERT INTO student(id,name) values(2,' Zhang San ');
4.2 Unique constraint
Ensure that the field is unique , It can be for null, Often set in non id Field
create table student(
id int(4) primary KEY,
name VARCHAR(20) UNIQUE,
age int UNIQUE
);
INSERT INTO student(id,name,age) values(1,' Zhang San ',22);
INSERT INTO student(id,name,age) values(2,' Zhang Xiaosan ',25);
4.3 Primary key self growth column
( Commonly used :primary KEY auto_increment)
create table student(
id int(4) primary KEY auto_increment,
name VARCHAR(20) UNIQUE,
age int
);
INSERT INTO student(name,age) values(' Kang Yang ',22);
INSERT INTO student(name,age) values(' Kangxiaoyang ',25);
INSERT INTO student(name,age) values(' Kangdayang ',28);
INSERT INTO student(id,name,age) values(8,' Kangzhongyang ',28);
INSERT INTO student(age) values(28);
explain : The primary key grows by itself , from 1 Start , Every time it's self increasing 1
Domain integrity constraints
Limit the data correctness of the cells in the column .
4.4 Non empty constraint
create table student(
id int(4) primary KEY auto_increment,
name VARCHAR(20) UNIQUE NOT NULL,
age int
);
4.5 Default constraint
create table student(
id int(4) primary KEY auto_increment,
name VARCHAR(20) UNIQUE NOT NULL,
age int default 30
);
INSERT INTO student(name,age) values(' Kang Yang ',22);
INSERT INTO student(name) values(' Kangxiaoyang ');
4.6 Referential integrity constraints ( Foreign key constraints )
Constraints in two tables
The primary key in the main table , It can be set as a foreign key in the slave table ; The value of the foreign key must be set to the value of the primary key
Set constraints from tables , Refer to the primary key of the main table
Be careful : When there is a reference relationship between two tables , To delete , Be sure to delete the slave table first ( Reference table ), Delete the main table ( Referenced table )
- Business ( a key )
summary : Transactions are often multiple sql binding , Either they all succeed , Then submit ; There is a failure , Then roll back
5.1. Analog transfer function
create table account(
id int PRIMARY key auto_increment,
name VARCHAR(20) UNIQUE NOT NULL,
money double(8,2)
);
select * from account;
insert into account(name,money) values(' Huangyupeng ',200000);
insert into account(name,money) values(' Chen Dao ',100000);
start TRANSACTION; Open transaction
update account set money=money-20000 where id=1;
// There may be an exception in the middle
update account set money=money+20000 where id=2;
commit; If all are successful, submit
ROLLBACK; If an exception occurs, rollback
5.2 How things work
After opening the transaction ,sql Statements are placed in the buffer ( Rollback segment ); Only all SQL Normal execution , Execute to commit, To write to the database
otherwise , If an exception occurs, it will be executed to rollback, Delete rollback segment
5.3 The nature of transactions (ACID)
Atomicity : An indivisible whole , Either everything succeeds , Or they all failed
Uniformity : Whether the transaction is successful or not , The overall data will not change
Isolation, : Threads in transactions , It is isolated from the threads of other operations , Not affecting each other
persistence : Once submitted , Is permanently written to the database
Application scenarios :
It is generally used in projects with high security , For example, financial projects , Mall project, etc
- Rights management ( understand )
scene : You are usually assigned a non administrator account in the company , May only be responsible for querying or adding
Create a zs Users of
create user 'zs' IDENTIFIED by '123';
User authorization
GRANT ALL ON mydb1.account TO 'zs';
Revoke user privileges
REVOKE ALL on mydb1.account from 'zs';
Delete user
drop user 'zs';
You can also perform graphical user management operations
边栏推荐
- A compiler related bug in rtklib2.4.3 B34
- 关于重放攻击和防御
- Strong push, quick start to software testing
- BGP experiment
- Post processing of multisensor data fusion using Px4 ECL
- 小时候 觉得爸爸就是天 无所不能~
- 气象绘图软件Panoply使用教程 (不定时更新)
- Baidu PaddlePaddle's "universal gravitation" first stop in 2022 landed in Suzhou, comprehensively launching the SME empowerment plan
- [microservices | Nacos] list of issues related to the Nacos version
- 账号多开是什么意思?为什么要账号多开?如何安全实现?
猜你喜欢

insert into... Where not exists insert to avoid repeated use

Seata四大模式之XA模式详解及代码实现

JVM原理之完整的一次GC流程

Hard core, become a high-quality tester: learn to communicate with products

stm32时钟树错误配置导致 开机进入硬中断

Visual display of TEQC quality analysis results using teqcplot

LeetCode 797:所有可能的路径

8 years' experience: monthly salary of 3000 to 30000, the change of Test Engineer

Strong push, quick start to software testing

VMware network connection error unit network service not found
随机推荐
CF【1700D】D. River Locks(dp、二分、数学)
insert into... Where not exists insert to avoid repeated use
BGP experiment
Web application security testing guide
Ams:startactivity desktop launch application
UI automation positioning edge -xpath actual combat
konva 系列教程 1:konva 是什么?
导出带水印的PDF
MCS:离散随机变量——Uniform分布
IDEA 代码开发完毕后,提交代码,提交后发现分支不对,怎么撤回
Jetpack Compose 从开门到入门之 MenuBar桌面菜单(Desktop Menu)
JDBC入门学习(二)之封装工具类
Drag and drop拖放框架
账号多开是什么意思?为什么要账号多开?如何安全实现?
Snippet Manager snippetslab
Drag and drop frame
Mmdeploy quick installation and instructions
104. 简易聊天室7:使用 Socket 传递对象
H5 adaptive full screen
What is the average annual salary of an outsourced tester who has worked for 5-8 years?