当前位置:网站首页>MySQL advanced (Advanced) SQL statement
MySQL advanced (Advanced) SQL statement
2022-07-04 11:48:00 【Jiudi aping】
MySQL senior ( Advanced ) SQL sentence
use kgc;
create table location (Region char (20) ,Store_ Name char (20)) ;
insert into location values(‘East’, ‘Boston’) ;
insert into location values(‘East’, ‘New York’);
insert into location values(‘West’, ‘Los Angeles’) ;
insert into location values (‘West’, ‘Houston’) ;
location form
±---------±-------------+
| Region| Store_ Name
|----------±-------------|
| East| BostonI
| East| New York|
| West| Los AngelesI
| West|Houston|
±---------±-------------+
create table store_ info (Store_ Name char (20) ,Sales int(10),Date char(10)) ;
insert into store_ info values(‘Los Angeles’, ‘1500’, ‘2020-12-05’);
insert into store_ info values (’ Houston’, ‘250’, ‘2020-12-07’);
insert into store_ info values(‘Los Angeles’, ‘300’, ‘2020-12-08’);
insert into store_ info values (‘Boston’, ‘700’, ‘2020-12-08’) ;
---- SELECT ---- Displays all data records for one or more fields in the table
grammar : SELECT “ Field ” FROM “ Table name ”;
SELECT Store_ Name FROM Store_ Info;
----DISTINCT---- Do not display duplicate data records
grammar : SELECT DISTINCT “ Field ” FROM “ Table name ”;
SELECT DISTINCT Store_ Name FROM Store_ Info;
----WHERE---- Conditional query
grammar : SELECT “ Field ” FROM “ Table name ” WHERE “ Conditions ”;
SELECT Store_ Name FROM Store_ Info WHERE Sales > 1000;
---- AND OR ---- And or
grammar : SELECT “ Field ” FROM “ Table name ” WHERE “ Conditions 1” { [ANDIOR] “ Conditions 2”}+ ;
SELECT Store_ Name FROM Store_ Info WHERE Sales > 1000 OR (Sales < 500 AND Sales > 200) ;
----IN---- Data records showing known values
grammar : SELECT “ Field ” FROM “ Table name ” WHERE “ Field ” IN (‘ value 1’, ‘ value 2’, …);
SELECT * FROM Store_ Info WHERE Store_ Name IN (‘Los Angeles’, ‘Houston’) ;
----BETWEEN---- Display data records in the range of two values
grammar : SELECT “ Field ” FROM " Table name ”WHERE " Field ”BETWEEN ‘ value 1’ AND ‘ value 2’;
SELECT*FROM Store_ Info WHERE Date BETWEEN ‘2020-12-06’ AND ‘2020-12-10’;
---- wildcard ---- Usually, wildcards are used with LIKE Used together
%: A percent sign means zero 、 One or more characters
_: The underline represents a single character
‘A_ 2’: All with ’A’ At first , Another character of any value , And in ’2’ String ending with . for example ,‘ABZ’ and ’A2Z2’ All conform to this pattern , and ’AKK2’
It does not accord with ( Because in A and Z There are two characters between , Instead of one character by one ).
‘ABC8’: All with ’ABC’ Starting string . for example ,‘ABCD’ and ’ABCABC’ All fit the pattern .
‘8XYZ’: All with ’XYZ’ a null-terminated string . for example ,‘WXYZ’ and ’ZZXYZ’ All fit the pattern .
‘&AN8’: All contain ’AN’ this String of patterns . for example ,‘LOS ANGELES’ and ’SAN FRANCISCO’ All fit the pattern .
‘_ AN%’: All the second letters are ’A’ And the third letter is ’N’ String . for example ,‘SAN FRANCISCO’ In line with this pattern , and ’LOS ANGELES’
It doesn't fit the pattern ..
---- LIKE ---- matching - A pattern to find the data record we want
grammar : SELECT “ Field ” FROM “ Table name ” WHERE “ Field ” LIKE { Pattern };
SELECT * FROM Store Info WHERE Store Name like ‘8os Number ’ ;
-----ORDER BY ---- Sort by keyword
grammar : SELECT “ Field ” FROM “ Table name ” [WHERE “ Conditions ”] ORDER BY “ Field ” [ASC, DESC];
#ASC It's sorted in ascending order , Is the default sort method .
#DESC It's sorted in descending order .
SELECT Store_ Name, Sales, Date FROM Store_ Info ORDER BY Sales DESC;
---- function ----
Mathematical functions :
abs (x) return x The absolute value of
rand () return 0 To 1 The random number
mod(x,y) return x Divide y The remainder after
power (x,y) return x Of y Power
round(x) Return from x The nearest integer
round(x,y) Retain x Of y The rounded value of a decimal place
sqrt (x) return x The square root of
truncate (x,y) Return to digital x Truncated to y A decimal value
ceil (x) Returns greater than or equal to x Minimum integer of
floor (x) Returns less than or equal to x Maximum integer for
greatest (x1,x2…) Returns the maximum value in the collection
least (x1,x2…) Returns the smallest value in the set
SELECT abs(-1), rand(), mod(5,3), power(2,3), round(1.89) ;
SELECT round(1.8937,3), truncate (1.235,2),ceil(5.2), floor(2.1), least(1.89,3,6.1,2.1) ;
Aggregate functions :
avg() Returns the average value of the specified column
count () Returns the value of the specified column NULL The number of values
min() Returns the minimum value of the specified column
max () Returns the maximum value of the specified column
sum(x) . Returns the sum of all values in the specified column
SELECT avg (Sales) FROM Store_ Info;
SELECT count (Store_ Name) FROM Store Info;
SELECT count (DISTINCT Store Name ) FROM Store_Info;
SELECT max (Sales) FROM Store_ Info;
SELECT min (Sales) FROM Store_ Info;
SELECT sum (Sales) FROM Store Info;
City form
±---------+
|name|
|beijing |
| nanjing |
|shanghai |
|<null>|
|<null>|
±-----------+
SELECT count (name) FROM City;
SELECT count(*) FROM City;
#count(*) Including the number of rows of all columns , When it comes to statistical results , Column values of... Are not ignored NULL
#count ( Name ) Only the column name - Number of rows in the column , When it comes to statistical results , Column values of NULL The line of
String function :
trim() Returns a value with the specified format removed
concat (x,y) The parameters that will be provided x and y Concatenate into a string
substr(x,y) Get from string x No y A string starting at a position , Follow substring () Functions work the same
substr(x,y,z) Get from string x No y The starting length of a position is z String
length(x) . Return string x The length of
replace (x,y,z) The string z Alternative string x String in y
upper (x) The string x All of the letters of the alphabet become capital letters
lower (x) The string x All of the letters of the are changed into lower case letters
left(x,y) Return string x Before y Characters
right (x,y) Return string x After y Characters
repeat (x,y) The string x repeat y Time
space (x) return x A space
strcmp(x,y) Compare x and y, The value returned can be -1,0,1
reverse (x) The string x reverse
SELECT concat (Region,Store_ Name) FROM location WHERE Store_ Name = ‘Boston’ ;
# Such as sq1_mode Open the PIPES_ AS_ CONCAT,"I1" Treat as the concatenation operator of a string, not as the or operator , And string splicing function Concat Similar , This sum Oracle The database is used in the same way
SELECT Region II ’ ’ 1 Store_ Name FROM location WHERE Store_ Name = ‘Boston’ ;
SELECT substr (Store Name,3) FROM location WHERE Store_ Name = ‘Los Angeles’ ;
SELECT substr (Store_ Name,2,4) FROM location WHERE Store_ Name = ‘New York’;
SELECT TRIM ([ [ Location ] [ The string to remove ] FROM ] character string );
#[ Location ]: The value of can be LEADING ( At first ),TRAILING ( ending ), BOTH ( The beginning and the end ).
#[ The string to remove ]: From the beginning of the string 、 ending , Or a string removed from the beginning and end . The default is space .
SELECT TRIM (LEADING ‘Ne’ FROM ‘New York’) ;
SELECT Region, length (Store_ Name) FROM location;
SELECT REPLACE (Region, ‘ast’, ‘astern’) FROM location;
----GROUPBY---- Yes GROUPBY The query results of the following fields are summarized and grouped , Usually used in combination with aggregate functions
GROUPBY There is a ” Principles , Namely SELECT In all the following columns , Columns that do not use aggregate functions , Must appear in GROUPBY Back .
grammar : SELECT “ Field 1”,SUM(“ Field 2”) FROM “ Table name ” GROUP BY “ Field 1”;
SELECT Store_ Name, SUM(Sales) FROM Store_ Info GROUP BY Store_ Name ORDER BY sales desc;
----HAVING ---- Used to filter by GROUP BY language The record set returned by the , Usually with GROUP BY Statements are used in conjunction with
HAVING The existence of sentences makes up for WHERE Keywords cannot be combined with aggregate functions . If you are SELECT Only the function bar , Then there is no need for GROUP BY Clause .
grammar : SELECT “ Field 1”, SUM(“ Field 2”) FROM “ Table name ” GROUP BY “ Field 1” HAVING ( Function conditions );
SELECT Store_ Name,SUM(Sales) FROM Store_ Info GROUP BY Store_ Name HAVING SUM (Sales) > 1500;
---- Alias ---- Field alias table alias
grammar : SELECT “ Form alias ”. " Field 1”[AS] " Field alias ”FROM “ Table name ” [AS] “ Form alias ”;
SELECT A. Store_ Name Store, SUM(A.Sales) “Total Sales” FROM Store_ Info A GROUP BY A.Store Name;
---- Subquery ---- Connect tables , stay WHERE Clause or HAVING Clause to insert another SQL sentence
grammar : SELECT " Field 1”FROM " form 1”WHERE " Field 2”[ Comparison operator ] # External query
(SELECT “ Field 1” FROM “ form 2” WHERE “ Conditions ”); # Internal query
# Can be symbolic operators , for example =、>、<. >=、<= ; It can also be a literal operator , for example LIKE、IN、 BETWEEN
SELECT SUM(Sales) FROM Store_ Info WHERE Store_ Name IN
(SELECT Store_ Name FROM location WHERE Region = ‘West’) ;
SELECT SUM(A.Sales) FROM Store_ Info A WHERE A.Store Name IN
(SELECT Store_ Name FROM location B WHERE B.Store_ Name = A.Store_ Name) ;
---- EXISTS ---- It is used to test whether the inner query produces any results , Whether Boolean value is true or not
# If any , The system will execute the SQL sentence . If not , The whole SQL Statement will not produce any results .
grammar : SELECT “ Field 1” FROM “ form 1” WHERE EXISTS(SELECT * FROM " form 2”WHERE “ Conditions ”);
SELECT SUM(Sales) FROM Store_ Info WHERE EXISTS (SELECT * FROM location WHERE Region = ‘West’);
Link query
location form
±---------±-------------+
I Region I Store_NameI
| ----------±-------------I
| EastI Boston|
|East| New York|
| West| Los Angeles|
| West| Houston|
±---------±-------------+
UPDATE Store_ Info SET store_ name= ‘Washington’ WHERE sales=300;
Store_ Info form .
| Store_ Name Sales | Date|
| Los Angeles|50012020-12-05|
| Houston250 | 2020-12-07 |
| Washington300 | 2020-12-08 |
| Boston700 | 2020-12-08 |
inner join( Internal connection ): Only rows with equal join fields in two tables are returned
leftjoin( Left connection ): Returns records that include all records in the left table and join fields in the right table
rightjoin( The right connection ): Returns records that include all records in the right table and join fields in the left table
SELECT*FROM location A INNER JOIN Store Info B on A.Store Name = B. Store Name ;
SELECT * FROM location A RIGHT JOIN Store Info B on A.Store Name = B. Store Name ;
SELECT*FROM location A,Store_ Info B WHERE A.Store Name = B.Store Name;
SELECT A. Region REGION, SUM(B.Sales) SALES FROM location A,Store_ Info B
WHERE A.Store Name = B.Store Name GROUP BY REGION;
----CREATEVIEW---- View , It can be thought of as a virtual table or a storage query .
The difference between a view and a table is , There are actually stored data records in the form , The view is based on a table - Architectures , It itself does not actually store data records .
The temporary table disappears automatically when the user exits or loses the connection to the database , And the view doesn't disappear .
Views don't contain data , Just store its definition , Its purpose – It can simplify complex queries . For example, you need to query several tables , But also to carry out statistical sorting and other operations , Write SQL Sentences can be cumbersome , Join several tables with views , Then query the view , Just one-on-one - The same as a table query , Very convenient .
grammar : CREATE VIEW “ View table name ” AS “SELECT sentence ”;
CREATE VIEW V_ REGION_ SALES AS SELECT A. Region REGION, SUM(B.Sales) SALES FROM location A
INNER JOIN Store_ Info B ON A.Store_ Name = B.Store_ Name GROUP BY REGION;
SELECT * FROM V_ REGION SALES ;
DROP VIEW V_ REGION_ SALES ;
边栏推荐
- 2021 annual summary - it seems that I have done everything except studying hard
- How to deal with the relationship between colleagues
- Reptile learning 4 winter vacation learning series (1)
- Global function Encyclopedia
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 22
- 本地Mysql忘记密码的修改方法(windows)[通俗易懂]
- LxC shared directory permission configuration
- 'using an alias column in the where clause in PostgreSQL' - using an alias column in the where clause in PostgreSQL
- Configure SSH key to realize login free
- Local MySQL forgot the password modification method (Windows)
猜你喜欢
Automatic translation between Chinese and English
Global function Encyclopedia
Force buckle 142 Circular linked list II
Ternsort model integration summary
Failed to configure a DataSource: ‘url‘ attribute is not specified... Bug solution
2021-08-09
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 17
Usage of case when then else end statement
QQ group collection
Introduction to Lichuang EDA
随机推荐
Summary of Shanghai Jiaotong University postgraduate entrance examination module -- cryptography
LxC shared directory addition and deletion
Data transmission in the network
How to deal with the relationship between colleagues
Some tips on learning database
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
TCP fast retransmission sack mechanism
How to create a new virtual machine
03_ Armv8 instruction set introduction load and store instructions
QQ group collection
Force buckle 142 Circular linked list II
TCP slicing and PSH understanding
No response after heartbeat startup
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
Summary of collection: (to be updated)
World document to picture
Simple understanding of seesion, cookies, tokens
Introduction of network security research direction of Shanghai Jiaotong University
Cacti主机模板之定制版
Enter the smart Park, and change begins here