当前位置:网站首页>Mysql database - function constraint multi table query transaction
Mysql database - function constraint multi table query transaction
2022-07-04 07:27:00 【Super Xiao He】
Catalog
The joint query union, union all
function
String function
Common functions :
function | function |
---|---|
CONCAT(s1, s2, …, sn) | String splicing , take s1, s2, …, sn Concatenate into a string |
LOWER(str) | Convert all strings to lowercase |
UPPER(str) | Convert all strings to uppercase |
LPAD(str, n, pad) | padding-left , Use string pad Yes str Fill the left side of the , achieve n String length |
RPAD(str, n, pad) | Right fill , Use string pad Yes str Fill the right side of the , achieve n String length |
TRIM(str) | Remove the spaces at the beginning and end of the string |
SUBSTRING(str, start, len) | Return from string str from start It's from the position len A string of length |
-- Splicing
SELECT CONCAT('Hello', 'World');
-- A lowercase letter
SELECT LOWER('Hello');
-- Capitalization
SELECT UPPER('Hello');
-- padding-left
SELECT LPAD('01', 5, '-');
-- Right fill
SELECT RPAD('01', 5, '-');
-- Remove the space
SELECT TRIM(' Hello World ');
-- section ( The starting index is 1)
SELECT SUBSTRING('Hello World', 1, 5);
Numerical function
Common function :
function | function |
---|---|
CEIL(x) | Rounding up |
FLOOR(x) | Rounding down |
MOD(x, y) | return x/y The mold |
RAND() | return 0~1 The random number in |
ROUND(x, y) | Find parameters x Round the value of , Retain y Decimal place |
Date function
Common functions :
function | function |
---|---|
CURDATE() | Return current date |
CURTIME() | Return current time |
NOW() | Returns the current date and time |
YEAR(date) | Get specified date A year of |
MONTH(date) | Get specified date Month of |
DAY(date) | Get specified date Date |
DATE_ADD(date, INTERVAL expr type) | Return a date / Time value plus a time interval expr Time value after |
DATEDIFF(date1, date2) | Return to start time date1 And end time date2 Days between |
select curdate();
select curtime();
select now();
select year(now());
select month(now());
select day(now());
select date_add(now(),interval 70 day );
select datediff('2022-06-29','2022-06-01');
Flow function
Common functions :
function | function |
---|---|
IF(value, t, f) | If value by true, Then return to t, Otherwise return to f |
IFNULL(value1, value2) | If value1 Not empty , return value1, Otherwise return to value2 |
CASE WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END | If val1 by true, return res1,… Otherwise return to default The default value is |
CASE [ expr ] WHEN [ val1 ] THEN [ res1 ] … ELSE [ default ] END | If expr The value is equal to the val1, return res1,… Otherwise return to default The default value is |
select
name,
(case when age > 30 then ' middle-aged ' else ' youth ' end)
from employee;
select
name,
(case workaddress when ' The Beijing municipal ' then ' first-tier cities ' when ' Shanghai ' then ' first-tier cities ' else ' Second-tier cities ' end) as ' Work address '
from employee;
constraint
Common constraints
constraint condition | keyword |
---|---|
Primary key | PRIMARY KEY |
Automatic growth | AUTO_INCREMENT |
Not empty | NOT NULL |
only | UNIQUE |
Logical conditions | CHECK |
The default value is | DEFAULT |
create table user(
id int primary key auto_increment,
name varchar(10) not null unique,
age int check(age > 0 and age < 120),
status char(1) default '1',
gender char(1)
);
Foreign key constraints
Add foreign keys :
CREATE TABLE Table name (
Field name Field type ,
...
[CONSTRAINT] [ Name of the foreign key ] FOREIGN KEY( Foreign key field name ) REFERENCES Main table ( Name of main table )
);
ALTER TABLE Table name ADD CONSTRAINT Name of the foreign key FOREIGN KEY ( Foreign key field name ) REFERENCES Main table ( Name of main table );
-- Example
alter table emp add constraint fk_emp_dept_id foreign key(dept_id) references dept(id);
Delete foreign key :
ALTER TABLE Table name DROP FOREIGN KEY Foreign key name ;
Delete / Update behavior
Behavior | explain |
---|---|
NO ACTION | When deleting in the parent table / When updating the corresponding record , First, check whether the record has a corresponding foreign key , If there is, it is not allowed to delete / to update ( And RESTRICT Agreement ) |
RESTRICT | When deleting in the parent table / When updating the corresponding record , First, check whether the record has a corresponding foreign key , If there is, it is not allowed to delete / to update ( And NO ACTION Agreement ) |
CASCADE | When deleting in the parent table / When updating the corresponding record , First, check whether the record has a corresponding foreign key , If so, delete / Update the record of the foreign key in the sub table |
SET NULL | When deleting in the parent table / When updating the corresponding record , First, check whether the record has a corresponding foreign key , If yes, set the foreign key value in the sub table to null( The foreign key is required to be allowed to be null) |
SET DEFAULT | When the parent table changes , The child table sets the foreign key to a default value (Innodb I won't support it ) |
Change delete / Update behavior :
ALTER TABLE Table name ADD CONSTRAINT Name of the foreign key FOREIGN KEY ( Foreign key field ) REFERENCES Main table name ( Main table field name ) ON UPDATE Behavior ON DELETE Behavior ;
Multi-table query
Multi table relation
- One to many ( For one more )
- Many to many
- one-on-one
One to many
Case study : Departments and employees
Relationship : A Department corresponds to multiple employees , One employee corresponds to one department
Realization : Build foreign keys on more than one side , A primary key that points to a party of one
Many to many
Case study : Students and curriculum
Relationship : A student can take more than one course , A course can also be taken by multiple students
Realization : Create a third intermediate table , The middle table contains at least two foreign keys , Associate the primary keys of two parties respectively
one-on-one
Case study : User and user details
Relationship : One to one relationship , It is mostly used for single table splitting , Put the basic fields of a table in a table , Other detail fields are placed in another table , To improve operational efficiency
Realization : Add foreign keys on either side , Associated with the primary key of another party , And set the foreign key to be unique (UNIQUE)
Inquire about
Merge query ( The cartesian product , Will show all the combined results ):
select * from employee, dept;
The cartesian product : Two sets A The collection and B All combinations of sets ( In multi-table queries , You need to eliminate the invalid Cartesian product )
Eliminate invalid Cartesian product :
select * from employee, dept where employee.dept = dept.id;
Internal connection query
The inner join query is the part of the intersection of two tables
Implicit inner join :
SELECT Field list FROM surface 1, surface 2 WHERE Conditions ...;
Explicit inner connection :
SELECT Field list FROM surface 1 [ INNER ] JOIN surface 2 ON Connection condition ...;
Explicit performance is better than implicit
-- Check the name of the employee , And the name of the associated department
-- Implicit
select e.name, d.name from employee as e, dept as d where e.dept = d.id;
-- Explicit
select e.name, d.name from employee as e inner join dept as d on e.dept = d.id;
External connection query
The left outer join :
Query all data in the left table , And the intersection of two tables
SELECT Field list FROM surface 1 LEFT [ OUTER ] JOIN surface 2 ON Conditions ...;
Equivalent to query table 1 All data for , Include table 1 And table 2 Intersection part data
Right connection :
Query all data in the right table , And the intersection of two tables
SELECT Field list FROM surface 1 RIGHT [ OUTER ] JOIN surface 2 ON Conditions ...;
-- Left
select e.*, d.name from employee as e left outer join dept as d on e.dept = d.id;
select d.name, e.* from dept d left outer join emp e on e.dept = d.id; -- This statement has the same effect as the following statement
-- Right
select d.name, e.* from employee as e right outer join dept as d on e.dept = d.id;
The left connection can query whether there is dept Of employee, The right connection can be used to query whether employee Of dept
Self connect query
Query the connection between the current table and itself , Self join must use table alias
grammar :
SELECT Field list FROM surface A Alias A JOIN surface A Alias B ON Conditions ...;
Self connect query , It can be internal connection query , It can also be an external connection query
Example :
-- Query the names of employees and their leaders
select a.name, b.name from employee a, employee b where a.manager = b.id;
-- Those without leaders can also be found out
select a.name, b.name from employee a left join employee b on a.manager = b.id;
The joint query union, union all
Merge the results of multiple queries , Form a new query set
grammar :
SELECT Field list FROM surface A ...
UNION [ALL]
SELECT Field list FROM surface B ...
matters needing attention
- UNION ALL There will be duplicate results ,UNION Can't
- Joint queries are better than using or Efficient , Will not invalidate the index
Subquery
SQL Nested in statement SELECT sentence , Nested query , Also known as subquery .
SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM t2);
The statement outside the subquery can be INSERT / UPDATE / DELETE / SELECT Any one of
According to the sub query results, it can be divided into :
- Scalar subquery ( The subquery result is a single value )
- Column query ( The subquery result is a column )
- Line sub query ( The sub query result is one line )
- Table sub query ( The sub query result is multi row and multi column )
According to the sub query location, it can be divided into :
- WHERE after
- FROM after
- SELECT after
Scalar subquery
The result returned by the subquery is a single value ( Numbers 、 character string 、 Date, etc. ).
Common operators :- < > > >= < <=
Example :
-- Query all employees in the Sales Department
select id from dept where name = ' The sales department ';
-- According to the Sales Department ID, Query employee information
select * from employee where dept = 4;
-- Merge ( Subquery )
select * from employee where dept = (select id from dept where name = ' The sales department ');
-- Inquire about xxx Employee information after employment
select * from employee where entrydate > (select entrydate from employee where name = 'xxx');
Column query
The result returned is a column ( It can be multiple lines ).
Common operators :
The operator | describe |
---|---|
IN | Within the specified set , A commonplace |
NOT IN | Not within the specified set |
ANY | The subquery returns to the list , Any one can be satisfied |
SOME | And ANY equivalent , Use SOME Can be used everywhere ANY |
ALL | All values of the list returned by the subquery must meet |
Example :
-- Query all employee information of sales department and marketing department
select * from employee where dept in (select id from dept where name = ' The sales department ' or name = ' The Marketing Department ');
-- Inquire about employees who are paid more than everyone in the finance department
select * from employee where salary > all(select salary from employee where dept = (select id from dept where name = ' Finance Department '));
-- Query the information of employees whose salary is higher than that of any one in the R & D department
select * from employee where salary > any (select salary from employee where dept = (select id from dept where name = ' R & D department '));
Line sub query
The result is a line ( It can be multiple columns ).
Common operators :=, <, >, IN, NOT IN
Example :
-- Query and xxx The salary and the same employee information as the direct leader
select * from employee where (salary, manager) = (12500, 1);
select * from employee where (salary, manager) = (select salary, manager from employee where name = 'xxx');
Table sub query
The result is multiple rows and columns
Common operators :IN
Example :
-- Query and xxx1,xxx2 Employees with the same position and salary
select * from employee where (job, salary) in (select job, salary from employee where name = 'xxx1' or name = 'xxx2');
-- The date of employment inquiry is 2006-01-01 Later employees , And its department information
select e.*, d.* from (select * from employee where entrydate > '2006-01-01') as e left join dept as d on e.dept = d.id;
Business
A transaction is a collection of operations , The transaction will submit or revoke the operation request to the system as a whole , That is, these operations either succeed at the same time , Or fail at the same time .
Basic operation :
-- 1. Check Zhang San's account balance
select * from account where name = ' Zhang San ';
-- 2. The balance of three accounts -1000
update account set money = money - 1000 where name = ' Zhang San ';
-- After this statement goes wrong, Zhang San Qian decreases, but Li Si qian does not increase
simulation sql sentence in wrong
-- 3. Transfer the balance of Li Si's account +1000
update account set money = money + 1000 where name = ' Li Si ';
-- View transaction submission method
SELECT @@AUTOCOMMIT;
-- Set the transaction submission method ,1 For automatic submission ,0 For manual submission , This setting is only valid for the current session
SET @@AUTOCOMMIT = 0;
-- Commit transaction
COMMIT;
-- Roll back the transaction
ROLLBACK;
-- After setting manual submission, the above code is changed to :
select * from account where name = ' Zhang San ';
update account set money = money - 1000 where name = ' Zhang San ';
update account set money = money + 1000 where name = ' Li Si ';
commit;
Operation mode II :
Open transaction :
START TRANSACTION or BEGIN TRANSACTION;
Commit transaction :
COMMIT;
Roll back the transaction :
ROLLBACK;
Examples of operation :
start transaction;
select * from account where name = ' Zhang San ';
update account set money = money - 1000 where name = ' Zhang San ';
update account set money = money + 1000 where name = ' Li Si ';
commit;
Four characteristics ACID
- Atomicity (Atomicity): Transaction is an indivisible minimum operation , All or nothing , All or nothing
- Uniformity (Consistency): When the transaction completes , All data must be kept in a consistent state
- Isolation, (Isolation): The isolation mechanism provided by the database system , Ensure that transactions run in an independent environment that is not affected by external concurrent operations
- persistence (Durability): Once a transaction is committed or rolled back , Its changes to the data in the database are permanent
Concurrent transactions
problem | describe |
---|---|
Dirty reading | One transaction reads data that has not been committed by another transaction |
It can't be read repeatedly | A transaction reads the same record one after the other , But the data read twice is different |
Fantasy reading | When a transaction queries data according to criteria , There is no corresponding data row , But when inserting data again , It is found that this line of data already exists |
Concurrent transaction isolation level :
Isolation level | Dirty reading | It can't be read repeatedly | Fantasy reading |
---|---|---|---|
Read uncommitted | √ | √ | √ |
Read committed | × | √ | √ |
Repeatable Read( Default ) | × | × | √ |
Serializable | × | × | × |
- √ Indicates that the problem will occur at the current isolation level
- Serializable Lowest performance ;Read uncommitted The highest performance , Data security is the worst
View transaction isolation level :
SELECT
Set the transaction isolation level :
SET [ SESSION | GLOBAL ] TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE };
SESSION It's the conversation level , Indicates that it is valid only for the current session ,GLOBAL Indicates that it is valid for all sessions
边栏推荐
- Blog stop statement
- The most effective futures trend strategy: futures reverse merchandising
- flask-sqlalchemy 循环引用
- Handwritten easy version flexible JS and source code analysis
- Selenium ide plug-in download, installation and use tutorial
- jdbc连接es查询的时候,有遇到下面这种情况的大神嘛?
- Literature collation and thesis reading methods
- Two years ago, the United States was reluctant to sell chips, but now there are mountains of chips begging China for help
- Crawler (III) crawling house prices in Tianjin
- NLP literature reading summary
猜你喜欢
A real penetration test
The most effective futures trend strategy: futures reverse merchandising
MySQL中的文本处理函数整理,收藏速查
Selenium ide plug-in download, installation and use tutorial
In the era of low code development, is it still needed?
Splicing plain text into JSON strings - easy language method
Rhcsa the next day
the input device is not a TTY. If you are using mintty, try prefixing the command with ‘winpty‘
Industrial computer anti-virus
Xcode 14之大变化详细介绍
随机推荐
Deep profile data leakage prevention scheme
用于压缩视频感知增强的多目标网络自适应时空融合
The cloud native programming challenge ended, and Alibaba cloud launched the first white paper on application liveliness technology in the field of cloud native
Finishing (III) - Exercise 2
win10微软拼音输入法输入文字时候下方不出现中文提示
What is the use of cloud redis? How to use cloud redis?
Unity 从Inspector界面打开资源管理器选择并记录文件路径
In the era of low code development, is it still needed?
The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
Electronic Association C language level 1 35, bank interest
Chapter 1 programming problems
电子协会 C语言 1级 35 、银行利息
How to buy financial products in 2022?
Latex中的单引号,双引号如何输入?
The most effective futures trend strategy: futures reverse merchandising
Knowledge payment applet dream vending machine V2
Rapidjson reading and writing JSON files
Centos8 install mysql 7 unable to start up
Valentine's Day is coming! Without 50W bride price, my girlfriend was forcibly dragged away...
[Flink] temporal semantics and watermark