Advanced query statement of mysql

 1. Preface

 2. Efficient query method

2.1 Specify the field to view

2.2 Check the fields without duplication 

2.3 where condition query

2.4 and and or increase the logical relationship

 2.5 Query the data in the value list

2.6 References between

2.7 like query method

2.8 Query by sorting method 

 3. Use function query

3.1 Mathematical functions commonly used in databases 

3.2 Aggregate functions 

3.3 String functions 

(1) Remove the character trim

(2) Intercept substr

(3) Field splicing 

(4) Return the character length length 

 (5) replace replace

 4. Advanced query statement

4.1 GROUP BY (for grouping and aggregation) 

 (1) Summary statistics

 (2) Summarize and accumulate its specified fields (digital classes)

  (3) Summarize and accumulate its specified fields (digital classes), and then perform descending order

4.2 HAVING filter

4.3 Alias ​​setting query 

 (1) Field alias

 (2) Table Alias

4.4 Self-join of tables

(1) Ranking without repeated values 

(2) Ranking with repeated values 

4.5 Subquery statement 

Subquery use upgrade 

  4.6 EXISTS

 5. Table join query

(1) Inner join inner join

 (2) left join left join

(3) right join right join 

 6. The use of view view

(1) View creation 

(2) Subsequent convenient operations provided by the view

(3) Classic definition problem: Can the view insert data 

 7. UNION Cascading

7.1 UNION (deduplication after merging)

7.2 UNION ALL (no duplication after merging) 

 8. Find the intersection value of tables and tables in multiple ways

8.1 Cascading View Intersection Values

8.2 Inner join intersect value 

(1) Do not repeat the intersection 

(2) Deduplication and intersection 

8.3 Use left join to find intersection value 

8.4 Intersection using right join 

 8.5 Using subqueries to find intersection values

8.6 Take non-intersection values

9. Case condition selection query statement 

 10. Use of regular expressions

10.1 Common types of sql regular expressions

10.2 SQL Regular Application 

 Exploration: The difference between a null value (NULL) and no value (' ')

 1. Preface to this article
A database is a tool used to store, update, and query data, and querying data is the core function of a database. The database is used to carry information, and the information is used for analysis and viewing. Therefore, it is necessary to master a more refined query method. This article will focus on advanced query statements for data. 

For the use of the following query statements, two tables are prepared in advance, and some changes will be made to the tables or new tables will be created later according to the use of query functions: 

CREATE TABLE info (
  id int(4) ,
  name char(4),
  height double 
) ;
 
 
CREATE TABLE info2 (
  name char(4) 
  hobby char(10) 
  date char(10)
) ;


 2. Efficient query method
2.1 Specify the field to view
select field 1, field 2 from table name;
 

2.2 Deduplicate the fields and view 
 SELECT DISTINCT "field" FROM "table name";
 

2.3 where condition query
 SELECT "field" FROM table name" WHERE "condition";
 

2.4 and and or increase the logical relationship
 SELECT "field" FROM "table name" WHERE "condition 1" AND "condition 2";


 SELECT "Field" FROM "Table Name" WHERE "Condition 1" OR "Condition 2";
 

 2.5 Query the data in the value list
 SELECT "field" FROM "table name" WHERE "field" IN ('value 1', 'value 2', ...); #in, traverse a value list
 

2.6 reference between
 SELECT "field" FROM "table name" WHERE "field" BETWEEN 'value 1' AND 'value 2';
 

2.7 like query method
 like query is usually used in conjunction with wildcards

%: The percent sign represents zero, one or more characters

 _: A dash represents a single character

select * from info2 where hobby like '%ing';
select * from info2 where name like '小_';


 select * from info2 where name like '_刚';
 
select * from info2 where hobby like '%ay%';


2.8 sorting method to query 
order by, sort by keyword.

Notice:

Normally sorts numeric fields.
If you sort a field of type character, it sorts alphabetically.
 SELECT "field" FROM "table name" [WHERE "condition"] ORDER BY "field" [ASC|DESC] ;
 #ASC is sorted in ascending order, which is the default sorting method.
 #DESC is sorted in descending order.
  select * from info order by height;
  select * from info order by height asc;
  select * from info order by height desc;
 

 3. Use function query
3.1 Commonly used mathematical functions in the database Mathematical function 
function
abs(x) returns the absolute value of x
rand() returns a random number from 0 to 1
mod(x, y) returns the remainder after dividing x by y power
( x, y) Return x raised to the yth power
round(x) Return the nearest integer to x
round(x, y) Keep x’s y-digit rounded value
sqrt(x) Return the square root of x
truncate(x, y) Returns the value of the number x truncated to y decimal places #Do not round off
ceil(x) Returns the smallest integer greater than or equal to x
floor(x) Returns the largest integer less than or equal to x
greatest(x1,x2,...) Returns in the collection The largest value
least(x1,x2,...) Returns the smallest value in the collection
SELECT abs(-1),rand(), mod(5,3) ,power(2,3);


 SELECT truncate(1.89,2);
SELECT truncate(1.89,1);
 

select ceil(1.76);
select floor(1.76);


select greatest(1,2,3,55,12,55,61);
select least(1,2,3,55,12,55,61);


3.2 Aggregate function 
Aggregate function Meaning
avg() Returns the average value of the specified column
count() Returns the number of non-NULL values ​​in the specified column
min() Returns the minimum value of the specified column
max() Returns the maximum value of the specified column
sum(field) Returns the sum of all values ​​in the specified column
select avg(height) from info;


select count(name) from info;
select count(*) from info;
 

select max(height) from info;
select min(height) from info;
select sum(height) from info;


3.3 String functions 
String functions function
trim() returns the value without the specified format
concat(x,y) concatenates the provided parameters x and y into a string
substr(x,y) obtains the yth value from the string x The string starting from position 1 is the same as the substring() function
substr(x,y,z) Gets the string whose length is z starting from the yth position in the string x
length(x) returns the length of the string x
replace(x,y,z) replaces string z with string y in string x
upper(x) converts all letters in string x to uppercase
lower(x) converts all letters in string x to lowercase letter
left(x,y) returns the first y characters of the string x
right(x,y) returns the last y characters of the string x
repeat(x,y) repeats the string x y times
space(x) returns x spaces
strcmp(x,y) compare x and y, the returned value can be -1,0,1
reverse(x) reverse the string x
(1) remove the characters trim
 SELECT TRIM ([[position][to shift Divide String] FROM ] String)
 ;
 #[Position]: The value can be LEADING (beginning), TRAILING (end), BOTH (beginning and ending). 
 #[String to remove]: The string to remove from the beginning, end, or both of the beginning and end of the string. The default is blank.
select trim(leading 's' from 'swmming' );
select trim(trailing 'g' from 'swmming' );
select trim(both 'l' from 'lol' );


(2) Intercept substr
substr(x,y) #Intercept the x string from the yth to the end
 
substr(x,y,z) #Intercept the x string from the yth, the interception length is z
 
 
select substr(hobby,2) from info2;
select substr(hobby,3) from info2;


 select substr(hobby,2,5) from info2;
 select substr(hobby,4,6) from info2;
 

(3) Field splicing 
 1) concat(x,y)

select concat(name,height) from info;


 2) Use the || symbol

 #Stitch together the name field value and height field value in the info table.
 select name || height from info;
 

 #In the info table, the name field value and the height field value are spliced ​​together, and a space is added in the middle.
 select name || ' ' || height from info;
 

(4) Return character length length 
 select length(hobby) from info2;
 
 

 (5) Replace replace
select replace(name,'small','big') from info2;


 4. Advanced query statement
4.1 GROUP BY (for grouping and summarizing) 
summarizes and groups the query results of the fields behind GROUP BY, and is usually used in combination with aggregate functions

"GROUP BY" has a principle that all fields that appear after "GROUP BY" must appear after SELECT;

Any field that appears after SELECT and does not appear in the aggregation function must appear after "GROUP BY".

 (1) Summary statistics
select name, count(name) from info group by name;


 (2) Summarize and accumulate its specified fields (digital classes)
select name,sum(saving) from info3 group by name;


  (3) Summarize and accumulate the specified fields (numbers), and then
select name,sum(saving) from info3 group by name order by sum(saving) desc in descending order;


4.2 HAVING filter
Used to filter the recordset returned by the "GROUP BY" statement, usually used in conjunction with the "GROUP BY" statement.

The existence of the HAVING statement makes up for the deficiency that the WHERE keyword cannot be used in conjunction with aggregate functions.

where can only filter the fields in the original table, and cannot filter the results after group by.

 SELECT field 1,SUM(field 2) FROM "table name" GROUP BY field 1 HAVING(function condition) ;
select name,sum(saving) from info3 group by name having sum(saving)>1500;


4.3 Alias ​​setting query 
 syntax format: 

 SELECT field 1, field 2 AS field 2 alias from table name; #AS can be omitted
 (1) field alias
select name, sum(saving) as total_saving from info3 group by name having sum(saving)>1000;
select name ,sum(saving) as total_saving from info3 group by name having total_saving>1000;


 (2) Table alias
SELECT table alias. Field 1 [AS] field alias FROM table name [AS] table alias; #AS can be omitted


4.4 Self-joining of tables
(1) Ranking without repeated values 
​​Perform saving comparison and ranking on the following tables through self-joining of tables 

 Principle analysis and operation ideas of self-connection of tables to achieve ranking:

1. Take the above data table as an example, assuming that there are four people in total, and the amounts in their hands are different. We've done a self-join of the tables.

2. Use count to count, only count the number of people who are greater than or equal to the amount in your hand, for example, Xiao Ming with 2000, there is only one person greater than or equal to him, the count value can also be used as his ranking

3. Another example is Xiaohong with 800. If there are 4 people who are greater than or equal to her, the count value should be 4. Similarly, it can be proved that she is ranked fourth.

select A.name,A.saving,count(A.saving) as rank from info3 as A,info3 as B where A.saving <=B.saving group by A.name,A.saving  order by rank asc;
 

(2) There is 
a new demand list with duplicate numerical rankings: 

select A.name,A.saving,count(A.saving) as rank from info3 as A,info3 as B where A.saving < B.saving or (A.name=B.nameme and A.saving=B.saving) group by A.name,A.saving  order by rank asc;


4.5 Subquery statement 
Subquery: join tables, insert another SQL statement in WHERE clause or HAVING clause. 

 SELECT "Field 1" FROM "Table 1" WHERE "Field 2" [comparison operator] #Outer query
 (SELECT "Field 1" FROM "Table 2" WHERE "Condition"); #Inner query
Ordinary table data connection: 

select * from info as A, info3 as B where A.name=B.name;


Subquery join table join:

 select * from info where name in(select name from info3 where saving > 1000);


The subquery uses the upgrade 
to find the sum of all saving values ​​​​in the "Beijing area"

select sum(saving) from info3   where name in (select name from info  where address='北京');

select sum(saving) from info3   where name in (select name from info  where address='北京');
 

  4.6 EXISTS
 

Used to test whether the inner query produced any results, similar to whether a boolean value is true.
If the inner query has a result, the system will execute the SQL statement in the outer query. If there is no result, the entire SQL statement will not produce any results.
 

Format: 

 SELECT "Field 1" FROM "Form 1" WHERE EXISTS (SELECT * FROM "Form 2" WHERE "Condition");
 

 5. Table connection query
There are three types of table connection commonly used in MYSQL database:

Inner join (inner join): Only return rows with equal join fields in the two tables (with intersection values)
 

left join (left join): Returns records including all records in the left table and the join fields in the right table
A left join B: A is the left table, B is the right table
 

right join (right join): returns records including all the records in the right table and the join fields in the left table are equal
A right join B: A is the left table, B is the right table


 

(1) inner join
select * from info A inner join info3 B on A.name = B.name;
 
 

 Other ways to implement inner joins:

 select * from info A, info3 B where A.name=B.name;
 select * from info A inner join info3 B using(name);
 

 (2) left join left join
 

select * from info A LEFT JOIN info3 B on A.name=B.name;
 

(3)右连接 right join 
select * from info3 A right join info B on A.name=B.name ;
 

 6. The use of view view
 

Views: Can be thought of as virtual tables or stored queries.

The difference between a view and a table is that the table actually stores data records, while the view is a structure built on the table, and it does not actually store data records.
Temporary tables disappear automatically after the user logs out or the connection to the database is disconnected, but the view does not disappear.
A view does not contain data, only its definition is stored, and its use generally simplifies complex queries. For example, if you want to perform join queries on several tables, and also perform statistical sorting operations, it will be very troublesome to write SQL statements. Using a view to join several tables, and then performing query operations on this view is the same as performing operations on a table. Queries are the same, very convenient.
 

Format:

CREATE VIEW "view table name" AS "SELECT statement"; #create view table
 ​DROP
 VIEW "view table name"; #delete view table
 

(1) View creation 
 

Creation requirements: Create a view independently to count info and info3 between the two tables, first summarize the address of the name, and then calculate the sum of the savings of the region. It is required to reflect two fields of address and sum (sving)

create view v_address_saving as select A.address,sum(B.saving) total_saving from info A inner join info3 B on A.name=B.name group by address;
 
 

Data validation for view creation:

(2) Subsequent convenient operations provided by the view
 

 Benefits of views: Although the process of creating a view is the same as that of an advanced query statement (combining conditions and dividing two select statements to generate a derived table), the process is complicated, but if the query operation needs to be used frequently, creating a view is very useful Necessary, it can not only simplify the query process, but also perform further operations on the query, and it is very convenient.

 Further requirements: need to calculate the sum of savings in Suzhou and Shanghai

elect sum(total_saving) as suzhou_shanghai_saving from v_address_saving where address='苏州'or address='上海';
 

(3) Classic definition problem: Can the view insert data 
 

Whether a view can insert data depends on the situation: 

1) If the view table is a join query of two tables (for example, the A field of the view comes from the A table, and the B field comes from the B table, the data cannot be inserted). Because the table structure is inconsistent with the original table. The fields in the view are new fields generated through function operations based on a certain field in the original table, but there is no field that can actually be stored, so the data cannot be inserted.

2) If the structure of the view table is consistent with the original table, data can be inserted. The inserted data is stored in the original table, and the data updated by the view is actually the data mapped to the original table.

show create view analyzes the process of creating a view: 

 7. UNION Concatenation
UNION union set: Combine the results of two SQL statements, and the fields generated by the two SQL statements need to be the same type of data records.

7.1 UNION (deduplication after merging)
 

The resulting data record values ​​will not be duplicated and will be sorted according to the order of the fields. # Deduplication after merging

 Format: [select statement 1] UNION [select statement 2];

select name from info union select name from  info3;
 

7.2 UNION ALL (no duplication after merging) 
 

select name from info union all select name from  info3;
 

 8. Find the intersection value of tables and tables in multiple ways
8.1 Find the intersection value of the cascaded view
 

 
create view v_info as select distinct name from info union all select distinct name from info3;
 ​
select name,count(*) from v_info group by name;
 ​
 
select name from v_info group by name having count(*) >1;
 
 

8.2 Inner join intersect value 
 

(1) Do not repeat the intersection 
select A.name from info A inner join info3 B on A.name=B.name;
 ​select
A.name from info A inner join info3 B using(name);
 
 

(2) Deduplication and intersection 
select distinct A.name from info A inner join info3 B using(name);
 

8.3 Use left join to find intersection value 
 

select * from info A left join info3 B using(name);
select distinct A.name from info A left join info3 B using(name) where B.name is not null;
 

8.4 Intersection using right join 
 

 #Use the right join to find the intersection value of the store_name field, and then remove the duplicate
 select * from info A right join info3 B using(name);
 select distinct A.name from info A right join info3 B using(name) where A.name is not null;
 
 ​or
 select distinct A.name from info A right join info3 B on A.name=B.name where A.name is not null;
 
 

 8.5 Using subqueries to find intersection values
 

select distinct name from info where name in (select name from info3);


8.6 Take non-intersection values
 

(1) count(*)<=1 in cascade method

  (2) Left and right inner connections change is not null to is null

(3) Subquery outer join query not in (inner join query)

9. Case condition selection query statement 
 

 SELECT CASE ("field name")
     WHEN "condition 1" THEN "result 1"
     WHEN "condition 2" THEN "result 2"
     [ELSE "result N"]
     END
 FROM "table name";
     
 # "condition" can be a value or a formula. The ELSE clause is not required.
 

mysql> select address,case address
    -> when '上海' then height-10
    -> when '北京' then height+5
    -> else height+10
    -> end
    -> "new_height",name
    -> from info;
 

 10. The use of regular expressions
10.1 Common types of sql regular expressions
 

Regular symbol Function
^ Match the beginning character of the text
$ Match the end character of the text
. Match any single character
* Match zero or more characters in front of it
+ Match the character in front of it 1 or more times
String Match contains the specified string
l Or, when the preceding "|" is not true, it will match the following string
[...] Match any character in the character set
[^...] Match any character that is not in brackets
{n} Match the previous character The string n times
{n,m} matches the previous string at least n times and at most m times
 

10.2 SQL Regular Application 
 

Format:

select "field" from "table name" where "field" regexp 'regular expression';
 

 Exploration: The difference between empty value (NULL) and no value (' ')
The length of no value is 0, which does not take up space; while the length of NULL value is NULL, which takes up space.

IS NULL or IS NOT NULL is used to judge whether the field is NULL or not NULL, and cannot find out whether it has no value.

Use =' ' or < >' ' to handle the judgment of no value. <> represents not equal to.

When specifying the number of rows counted by the field through count (), if a NULL value is encountered, it will be automatically ignored, and if no value is encountered, it will be added to the record for calculation.

Guess you like

Origin blog.csdn.net/zl965230/article/details/130625543