当前位置:网站首页>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

  1. 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

  1. First query ‘King’ Department No ( Multi row single row )
select department_id from t_employees where last_name='King';
  1. The query again 80、90 Employee information of department No
select * from t_employees where department_id in (80,90);
  1. 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

  1. Sort the salaries of all employees first ( Sorted temporary table )
select * from t_employees ORDER BY salary DESC;
  1. 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;

  1. 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;
  1. 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;

  1. 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 )

  1. 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

  1. 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

原网站

版权声明
本文为[The silent Lord returns to the sand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230309305829.html