当前位置:网站首页>Slightly more complex queries
Slightly more complex queries
2022-06-09 22:10:00 【ScrapingBoy】
Slightly more complex queries
After the note No more pasting pictures , It is troublesome to charge for the drawing bed , Determined not to use .
List of articles
1. View
As I mentioned earlier sql Basic query usage , Next, I will introduce some relatively complex usages .
Let's first look at a query statement :
SELECT product_name FROM view_product;
On the surface, this statement is exactly the same as the normal query data from the data table , But in fact, we operate a View . So from SQL From the point of view, the operation view and the operation table look exactly the same , So why is there a view ? What exactly is a view ? What's the difference between a view and a table ?
1.1 What is a view
A view is a virtual table , Unlike direct manipulation of data sheets , The view is based on SELECT Statement to create ( Will be described in detail below ), Therefore, when you operate the view, you will create the view according to SELECT Statement to generate a virtual table , Then do... On this virtual table SQL operation .
1.2 What is the difference between a view and a table
《sql Basic course No 2 edition 》 In one sentence, it concisely summarizes the difference between view and table —“ Whether the actual data is saved ”. So the view is not the data table actually stored in the database , It can be seen as a window , Through this window, we can see the real data in the database table . So we need to distinguish the essence of view and data table , That is, a view is a virtual table based on a real table , Its data sources are based on real tables .

picture source :《sql Basic course No 2 edition 》
The following doggerel is also convenient for you to remember the relationship between view and table :“ View is not a table , Views are virtual tables , Views depend on tables ”.
1.3 Why are there views
Now that there is a data sheet , Why do you need a view ? There are mainly the following reasons :
- By defining views, frequently used SELECT Statement save for efficiency .
- By defining views, users can see data more clearly .
- By defining the view, you can not expose all the fields of the data table , Enhance data confidentiality .
- Data redundancy can be reduced by defining views .
1.4 How to create a view
The basic syntax for creating a view is as follows :
CREATE VIEW < View name >(< Name 1>,< Name 2>,...) AS <SELECT sentence >
among SELECT Sentences need to be written in AS After keyword . SELECT The columns in the statement are arranged in the same order as the columns in the view , SELECT Regulation in statement 1 The column is the... In the view 1 Column , SELECT Regulation in statement 2 The column is the... In the view 2 Column , And so on . And the column name of the view is defined in the list after the view name . It should be noted that the view name should be unique in the database , Cannot have the same name as other views and tables .
Views can not only be based on real tables , We can also continue to create views based on views .
Although there are no errors in the syntax of continuing to create views on views , But we should try to avoid this kind of operation . This is because for most DBMS Come on , Multiview reduces SQL Performance of .
- matters needing attention
It should be noted that in general DBMS Cannot use... When defining views in ORDER BY sentence . It is wrong to define the view like this .
CREATE VIEW productsum (product_type, cnt_product)
AS
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type
ORDER BY product_type;
Test that the above statements can be executed .
Why can't I use ORDER BY Clause ? This is because views are the same as tables , Data rows are out of order .
stay MySQL The definition of view in is to allow the use of ORDER BY Of the statement , But if you choose from a specific view , This view uses its own ORDER BY sentence , Then... In the view definition ORDER BY Will be ignored .
- Views based on multiple tables
To learn multi table views , Let's create another table shop_product, The relevant code is as follows :
CREATE TABLE `shop_product`(
`shop_id` CHAR(4) NOT NULL,
`shop_name` VARCHAR(200) NOT NULL,
`product_id` CHAR(4) NOT NULL,
`quantity` INTEGER NOT NULL,
PRIMARY KEY (shop_id, product_id)
);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES
('000A', ' Tokyo ', '0001', 30),
('000A', ' Tokyo ', '0002', 50),
('000A', ' Tokyo ', '0003', 15),
('000B', ' Nagoya ', '0002', 30),
('000B', ' Nagoya ', '0003', 120),
('000B', ' Nagoya ', '0004', 20),
('000B', ' Nagoya ', '0006', 10),
('000B', ' Nagoya ', '0007', 40),
('000C', ' Osaka ', '0003', 20),
('000C', ' Osaka ', '0004', 50),
('000C', ' Osaka ', '0006', 90),
('000C', ' Osaka ', '0007', 70),
('000D', ' Fukuoka, ', '0001', 100);
out:
+---------+-----------+------------+----------+
| shop_id | shop_name | product_id | quantity |
+---------+-----------+------------+----------+
| 000A | Tokyo | 0001 | 30 |
| 000A | Tokyo | 0002 | 50 |
| 000A | Tokyo | 0003 | 15 |
| 000B | Nagoya | 0002 | 30 |
| 000B | Nagoya | 0003 | 120 |
| 000B | Nagoya | 0004 | 20 |
| 000B | Nagoya | 0006 | 10 |
| 000B | Nagoya | 0007 | 40 |
| 000C | Osaka | 0003 | 20 |
| 000C | Osaka | 0004 | 50 |
| 000C | Osaka | 0006 | 90 |
| 000C | Osaka | 0007 | 70 |
| 000D | Fukuoka, | 0001 | 100 |
+---------+-----------+------------+----------+
We are product Table and shop_product Create views based on tables :
CREATE VIEW view_shop_product(product_type, sale_price, shop_name)
AS
SELECT product_type, sale_price, shop_name
FROM product a,
shop_product b
WHERE a.product_id = b.product_id;
We can query based on this view :
SELECT sale_price, shop_name
FROM view_shop_product
WHERE product_type = ' clothes ';
out:
+------------+-----------+
| sale_price | shop_name |
+------------+-----------+
| 1000 | Tokyo |
| 4000 | Tokyo |
| 4000 | Nagoya |
| 4000 | Osaka |
| 1000 | Fukuoka, |
+------------+-----------+
5 rows in set (0.00 sec)
1.5 How to modify the view structure
The basic syntax for modifying the view structure is as follows :
ALTER VIEW < View name > AS <SELECT sentence >
The view name must be unique in the database , Cannot have the same name as other views and tables . Of course, you can also delete and recreate the current view to achieve the effect of modification .( Is this the same for the underlying database , You can explore for yourself )
- Modify the view
We modify the above productSum View is :
ALTER VIEW productSum
AS
SELECT product_type, sale_price
FROM Product
WHERE regist_date > '2009-09-11';
out:
+--------------+------------+
| product_type | sale_price |
+--------------+------------+
| clothes | 1000 |
| Kitchenware | 3000 |
| Kitchenware | 500 |
| Office Supplies | 100 |
+--------------+------------+
4 rows in set (0.00 sec)
1.6 How to update view content
Because the view is a virtual table , Therefore, the operation on the view is the operation on the underlying basic table , Therefore, only when the definition of the underlying basic table is met can the modification be successful .
For a view , If any of the following structures are included, they cannot be updated :
- Aggregate functions SUM()、MIN()、MAX()、COUNT() etc. .
- DISTINCT keyword .
- GROUP BY Clause .
- HAVING Clause .
- UNION or UNION ALL Operator .
- FROM Clause contains multiple tables .
In the final analysis, views are derived from tables , therefore , If the original table can be updated , that The data in the view can also be updated . vice versa , If the view changes , If the original table is not updated accordingly , There is no guarantee of data consistency .
- Update the view
Because we just modified productSum The view does not include the above restrictions , Let's try to update the view :
UPDATE productsum
SET sale_price = '5000'
WHERE product_type = ' Office Supplies ';
Now let's look at productSum View , You can find that the data has been updated :
+--------------+------------+
| product_type | sale_price |
+--------------+------------+
| clothes | 1000 |
| Kitchenware | 3000 |
| Kitchenware | 500 |
| Office Supplies | 5000 |
+--------------+------------+
4 rows in set (0.00 sec)
At this time, you can also find that the data has also been updated by observing the original table :
mysql> SELECT product_type, sale_price
-> FROM Product
-> WHERE regist_date > '2009-09-11';
+--------------+------------+
| product_type | sale_price |
+--------------+------------+
| clothes | 1000 |
| Kitchenware | 3000 |
| Kitchenware | 500 |
| Office Supplies | 5000 |
+--------------+------------+
4 rows in set (0.00 sec)
I wonder if you will have any questions when you see this result , When you just modified the view, you set product_type=' Office Supplies ’ Of goods sale_price=5000, Why is only one item of data in the original table modified ?
Or because of the definition of the view , The view is just a window of the original table , Therefore, it can only modify the content that can be seen through the window .
Be careful : Although the modification here is successful , However, this method of use is not recommended . Moreover, we also try to use restrictions when creating views. It is not allowed to modify tables through views
1.7 Delete view
The grammar is as follows :
DROP VIEW < View name 1> [ , < View name 2> …]
- Delete view
DROP VIEW productSum;
out:
mysql> DROP VIEW productSum;
Query OK, 0 rows affected (0.02 sec)
mysql> select * from productsum;
ERROR 1146 (42S02): Table 'shop.productsum' doesn't exist
mysql>
2. Subquery
Look at the following statement :
SELECT stu_name
FROM (
SELECT stu_name,
COUNT(*) AS stu_cnt
FROM students_info
GROUP BY stu_age) AS studentSum;
This statement looks very easy to understand , Which is enclosed in parentheses sql Statement executes first , After successful execution, execute the external sql sentence . But the view we mentioned in the previous section is also based on SELECT Statement to create a view, and then query on this basis . So what is a subquery ? What is the relationship between subquery and view ?
2.1 Definition
Subquery Refers to a query statement nesting A query inside another query statement , This feature comes from MySQL 4.1 Start introducing , stay SELECT The subquery is evaluated first in clause , The sub query results are used as filtering conditions for another query in the outer layer , Queries can be based on one table or more tables .
Be careful :
A subquery is the query that will be used to define the view SELECT Statements are used directly for FROM In the clause . among AS studentSum It can be regarded as the name of the subquery , And because the subquery is one-time , Therefore, subqueries are not saved on storage media like views , But in SELECT After the statement is executed, it disappears .
2.2 nested subqueries
Similar to redefining a view on a view , There are no specific restrictions on subqueries , For example, we can
SELECT product_type, cnt_product
FROM (SELECT *
FROM (SELECT product_type,
COUNT(*) AS cnt_product
FROM product
GROUP BY product_type) AS productsum
WHERE cnt_product = 4) AS productsum2;
The innermost sub query is named productSum, This statement is based on product_type Group and query the number , In the second level query, the number will be 4 Find out your products , Outermost query product_type and cnt_product Two . Although nested subqueries can find results , But with the superposition of the nested layers of subqueries ,SQL Not only will the statement be difficult to understand, but also the execution efficiency will be very poor , So try to avoid such use .
2.3 Scalar subquery
Scalar means single , So a scalar subquery is a single subquery , What is a single subquery ?
The so-called single is what we are required to perform SQL Statement can only return one value , That is to return the specific... In the table A column of a row . For example, we have the following table :
product_id | product_name | sale_price
------------+-------------+----------
0003 | motion T T-shirt | 4000
0004 | kitchen knife | 3000
0005 | pressure cooker | 6800
Then, after we execute a scalar subquery, we want to return something similar to ,“0004”,“ kitchen knife ” This is the result .
We now know that scalar quantum queries can return a value , So what does it do ?
It may be difficult to think so directly , Let's look at a few specific requirements :
- Find the goods whose sales unit price is higher than the average sales unit price
- Find out the product with the latest registration date
Do you have any ideas ?
Let's look at how to query the goods whose sales unit price is higher than the average sales unit price through scalar sub query statements .
SELECT product_id, product_name, sale_price
FROM product
WHERE sale_price > (SELECT AVG(sale_price) FROM product);
The above statement first finds out in the second half product The average selling price in the table , Ahead sql The statement is based on WHERE Select the right goods according to the conditions . Due to the nature of scalar subqueries , As a result, scalar subqueries are not limited to WHERE clause , In general, any location where a single value can be used can use . in other words , Where constants or column names can be used , Whether it's SELECT Clause 、GROUP BY Clause 、HAVING Clause , still ORDER BY Clause , It can be used almost everywhere .
We can also use scalar subqueries like this :
SELECT product_id,
product_name,
sale_price,
(SELECT AVG(sale_price)
FROM product) AS avg_price
FROM product;
Can you guess what the result of this code is ? Run it to see if it's consistent with what you think .
out:
+------------+--------------+------------+-----------+
| product_id | product_name | sale_price | avg_price |
+------------+--------------+------------+-----------+
| 0001 | T shirt | 1000 | 2710.0000 |
| 0002 | Punch | 500 | 2710.0000 |
| 0003 | motion T T-shirt | 4000 | 2710.0000 |
| 0004 | kitchen knife | 3000 | 2710.0000 |
| 0005 | pressure cooker | 6800 | 2710.0000 |
| 0006 | Fork | 500 | 2710.0000 |
| 0007 | Clean the board | 880 | 2710.0000 |
| 0008 | Ball pen | 5000 | 2710.0000 |
+------------+--------------+------------+-----------+
8 rows in set (0.01 sec)
2.4 Associated subquery
- What is an associated subquery
Since the association sub query contains two words , Then it must mean that there is a relationship between the query and the sub query . How was this connection established ?
Let's start with an example :
SELECT product_type, product_name, sale_price
FROM product AS p1
WHERE sale_price > (SELECT AVG(sale_price)
FROM product AS p2
WHERE p1.product_type = p2.product_type
GROUP BY product_type);
out:
+--------------+--------------+------------+
| product_type | product_name | sale_price |
+--------------+--------------+------------+
| clothes | motion T T-shirt | 4000 |
| Kitchenware | kitchen knife | 3000 |
| Kitchenware | pressure cooker | 6800 |
| Office Supplies | Ball pen | 5000 |
+--------------+--------------+------------+
4 rows in set (0.00 sec)
From the above example, we can probably guess , Associated sub query is to connect the internal and external queries through some flags to filter data , Next, let's take a look at the specific content of the associated sub query .
- Associate subqueries with subqueries
Remember our previous example Find the goods whose sales unit price is higher than the average sales unit price , In this case SQL The statement is as follows :
SELECT product_id, product_name, sale_price
FROM product
WHERE sale_price > (SELECT AVG(sale_price) FROM product);
out:
+------------+--------------+------------+
| product_id | product_name | sale_price |
+------------+--------------+------------+
| 0003 | motion T T-shirt | 4000 |
| 0004 | kitchen knife | 3000 |
| 0005 | pressure cooker | 6800 |
| 0008 | Ball pen | 5000 |
+------------+--------------+------------+
4 rows in set (0.00 sec)
Let's take another look at this demand Select the commodities that are higher than the average sales unit price of the commodity category .SQL The statement is as follows :
SELECT product_type, product_name, sale_price
FROM product AS p1
WHERE sale_price > (
SELECT AVG(sale_price)
FROM product AS p2
WHERE p1.product_type =p2.product_type));
Can you see the difference between the above two statements ?
In the second SQL Statement, that is, in the associated subquery, we will be outside product The table is marked as p1, Will be inside product Set to p2, And through WHERE Statement connects two queries .
However, if you just contact, you will be confused about the execution process of associated queries , Here's one Blog Speak more clearly . Here we briefly summarize as :
- First, execute without WHERE The main query of
- Match according to the main query result product_type, Get subquery results
- Combine the sub query results with the main query to execute the complete query SQL sentence
In subqueries, like scalar subqueries , Nested subquery or associated subquery can be regarded as an operation method of subquery .
Summary
Views and subqueries are the basic contents of database operation , For some complex queries, you need to use the combination of subqueries and some conditional statements to get the correct results . But anyway, for a SQL The number of layers that should not be designed for statements is very deep and particularly complex , Not only the readability is poor, but also the execution efficiency is difficult to guarantee , So try to have concise statements to complete the required functions .
Exercises
1. Create view
Create a view that meets the following three conditions ( The view name is view_product). Use product( goods ) Table as a reference table , Suppose the table contains the initial state of 8 Row data .
- Conditions 1: Sales unit price is greater than or equal to 1000 Yen .
- Conditions 2: The registration date is 2009 year 9 month 20 Japan .
- Conditions 3: Include product name 、 Sales unit price and registration date .
Execute... On the view SELECT The result of the statement is as follows .
create view view_product
as
select product_name, sale_price, regist_date
from product
where sale_price >= 1000
and regist_date = '2009-09-20';
out:
mysql> select * from view_product;
+--------------+------------+-------------+
| product_name | sale_price | regist_date |
+--------------+------------+-------------+
| T shirt | 1000 | 2009-09-20 |
| kitchen knife | 3000 | 2009-09-20 |
+--------------+------------+-------------+
2 rows in set (0.00 sec)
2.
View created in exercise 1 view_product Insert the following data , What kind of results will we get ? Why? ?
INSERT INTO view_product VALUES (' knife ', 300, '2009-11-02');
out:
ERROR 1423 (HY000): Field of view 'shop.view_product' underlying table doesn't have a default value
Generally speaking , The view cannot be augmented 、 Delete 、 Change , Views are only temporary results of queries , Not the underlying table .
3. Common functions
sql It comes with a variety of functions , Greatly improved sql The convenience of language .
So called functions , Like a black box , You give it an input value , It gives the return value according to the preset program definition , The input value is called Parameters .
Functions can be roughly divided into the following categories :
- Arithmetic functions ( A function used for numerical calculation )
- String function ( A function used to perform string operations )
- Date function ( Functions for date operations )
- Conversion function ( Functions used to convert data types and values )
- Aggregate functions ( Functions for data aggregation )
The total number of functions exceeds 200 individual , You don't have to remember , Common functions are 30~50 individual , For other functions that are not commonly used, you can consult the documentation .
3.1 Arithmetic functions
+ - * /The four operations were introduced in the previous chapter , No more details here .
To demonstrate several other arithmetic functions , In this construction samplemath surface
-- DDL : Create table
USE shop;
DROP TABLE IF EXISTS samplemath;
CREATE TABLE `samplemath`(
m NUMERIC(10,3),
n INT,
p INT
);
-- DML : insert data
START TRANSACTION; -- Start business
INSERT INTO samplemath(m, n, p) VALUES
(500, 0, NULL),
(-180, 0, NULL),
(NULL, NULL, NULL),
(NULL, 7, 3),
(NULL, 5, 2),
(NULL, 4, NULL),
(8, NULL, 3),
(2.27, 1, NULL),
(5.555,2, NULL),
(NULL, 1, NULL),
(8.76, NULL, NULL);
COMMIT; -- Commit transaction
out:
+----------+------+------+
| m | n | p |
+----------+------+------+
| 500.000 | 0 | NULL |
| -180.000 | 0 | NULL |
| NULL | NULL | NULL |
| NULL | 7 | 3 |
| NULL | 5 | 2 |
| NULL | 4 | NULL |
| 8.000 | NULL | 3 |
| 2.270 | 1 | NULL |
| 5.555 | 2 | NULL |
| NULL | 1 | NULL |
| 8.760 | NULL | NULL |
+----------+------+------+
11 rows in set (0.00 sec)
- ABS – The absolute value
grammar :ABS( The number )
ABS The function is used to calculate the absolute value of a number , Represents the distance from a number to the origin .
When ABS The argument to the function is NULL when , The return value is also NULL.
mysql> select abs(-12.56);
+-------------+
| abs(-12.56) |
+-------------+
| 12.56 |
+-------------+
1 row in set (0.00 sec)
- MOD – Mod
grammar :MOD( Divisor , Divisor )
MOD Is to calculate the remainder of division ( Seeking remainder ) Function of , yes modulo Abbreviation . The concept that decimals have no remainder , You can only remainder integer Columns .
Be careful : Mainstream DBMS All support MOD function , Only SQL Server The function is not supported , Its use % Sign to calculate the remainder .
mysql> select mod(16, 6) as res;
+------+
| res |
+------+
| 4 |
+------+
1 row in set (0.00 sec)
mysql> select mod(12.35, 5) as res;
+------+
| res |
+------+
| 2.35 |
+------+
1 row in set (0.00 sec)
- ROUND() – rounding
grammar :ROUND( Object value , Keep the number of decimal places )
ROUND The function is used for rounding .
Be careful : When parameters Keep the number of decimal places When is a variable , There may be mistakes , Use variables with caution .
mysql> select round(12.56);
+--------------+
| round(12.56) |
+--------------+
| 13 |
+--------------+
1 row in set (0.00 sec)
mysql> select round(12.5689, 2);
+-------------------+
| round(12.5689, 2) |
+-------------------+
| 12.57 |
+-------------------+
1 row in set (0.00 sec)
mysql> select round(3.14155, 4);
+-------------------+
| round(3.14155, 4) |
+-------------------+
| 3.1416 |
+-------------------+
1 row in set (0.00 sec)
SELECT m,
ABS(m) AS abs_col ,
n, p,
MOD(n, p) AS mod_col,
ROUND(m,1) AS round_col
FROM samplemath;
out:
+----------+---------+------+------+---------+-----------+
| m | abs_col | n | p | mod_col | round_col |
+----------+---------+------+------+---------+-----------+
| 500.000 | 500.000 | 0 | NULL | NULL | 500.0 |
| -180.000 | 180.000 | 0 | NULL | NULL | -180.0 |
| NULL | NULL | NULL | NULL | NULL | NULL |
| NULL | NULL | 7 | 3 | 1 | NULL |
| NULL | NULL | 5 | 2 | 1 | NULL |
| NULL | NULL | 4 | NULL | NULL | NULL |
| 8.000 | 8.000 | NULL | 3 | NULL | 8.0 |
| 2.270 | 2.270 | 1 | NULL | NULL | 2.3 |
| 5.555 | 5.555 | 2 | NULL | NULL | 5.6 |
| NULL | NULL | 1 | NULL | NULL | NULL |
| 8.760 | 8.760 | NULL | NULL | NULL | 8.8 |
+----------+---------+------+------+---------+-----------+
11 rows in set (0.00 sec)
3.1 String function
String functions are also often used , To learn string functions , Here we construct samplestr surface .
-- DDL : Create table
USE shop;
DROP TABLE IF EXISTS samplestr;
CREATE TABLE `samplestr`(
str1 VARCHAR (40),
str2 VARCHAR (40),
str3 VARCHAR (40)
);
-- DML: insert data
START TRANSACTION;
INSERT INTO samplestr (str1, str2, str3) VALUES ('opx', 'rt', NULL),
('abc', 'def', NULL),
(' The sun ', ' The moon ', ' Mars '),
('aaa', NULL, NULL),
(NULL, 'xyz', NULL),
('@!#$%', NULL, NULL),
('ABC', NULL, NULL),
('aBC', NULL, NULL),
('abc ha-ha ', 'abc', 'ABC'),
('abcdefabc', 'abc', 'ABC'),
('micmic', 'i', 'I');
COMMIT;
out:
mysql> select * from samplestr;
+-----------+------+------+
| str1 | str2 | str3 |
+-----------+------+------+
| opx | rt | NULL |
| abc | def | NULL |
| The sun | The moon | Mars |
| aaa | NULL | NULL |
| NULL | xyz | NULL |
| @!#$% | NULL | NULL |
| ABC | NULL | NULL |
| aBC | NULL | NULL |
| abc ha-ha | abc | ABC |
| abcdefabc | abc | ABC |
| micmic | i | I |
+-----------+------+------+
11 rows in set (0.00 sec)
- concat(str1,str2,…): Splicing
grammar :CONCAT(str1, str2, str3)
MySQL Use in CONCAT Function .
mysql> select concat('I', ' ', 'love', ' ', 'China', '!');
+---------------------------------------------+
| concat('I', ' ', 'love', ' ', 'China', '!') |
+---------------------------------------------+
| I love China! |
+---------------------------------------------+
1 row in set (0.00 sec)
- length()-- String length
grammar :LENGTH( character string )
mysql> select length('I love China!');
+-------------------------+
| length('I love China!') |
+-------------------------+
| 13 |
+-------------------------+
1 row in set (0.00 sec)
- lower()-- Lowercase conversion
LOWER Function can only be used for English letters , It converts all strings in the parameter to lowercase . This function is not applicable to situations other than English letters , Does not affect the original lowercase characters .
Allied , UPPER The function is used to convert to uppercase .
eg:
mysql> select lower('I love China!');
+------------------------+
| lower('I love China!') |
+------------------------+
| i love china! |
+------------------------+
1 row in set (0.00 sec)
mysql> select upper('I love China!');
+------------------------+
| upper('I love China!') |
+------------------------+
| I LOVE CHINA! |
+------------------------+
1 row in set (0.00 sec)
- replace() – String replacement
grammar :REPLACE( Object string , String before replacement , Replaced string )
select replace('5000-15000', '-', '~');
mysql> select replace('5000-15000', '-', '~');
+---------------------------------+
| replace('5000-15000', '-', '~') |
+---------------------------------+
| 5000~15000 |
+---------------------------------+
1 row in set (0.00 sec)
- substring(str FROM pos FOR len) – String truncation
grammar :SUBSTRING ( Object string FROM Intercept start position FOR Number of characters intercepted )
Use SUBSTR function You can truncate part of the string . The starting position of the interception is calculated from the leftmost side of the string , The index value starts with 1.
select substring('5000-15000' from 1 for 4)
+-----------------------------------+
| substring('5000-15000' from 1 for 4) |
+-----------------------------------+
| 5000 |
+-----------------------------------+
1 row in set (0.00 sec)
- SUBSTRING_INDEX(str, delim, count)– The string is truncated by index **
grammar :SUBSTRING_INDEX ( Original string , Separator ,n)
This function is used to obtain the original string, which is divided according to the separator , The first n Before a separator ( Or after ) Substring of , Supports forward and reverse indexing , The initial values caused by the cable are 1 and -1. If count Being positive , All contents to the left of the last separator are returned ( Count from the left ). If count It's a negative number , All contents to the right of the last separator are returned ( Count from the right ).
select substring_index('5000-16000', '-', 1);
out:
+---------------------------------------+
| substring_index('5000-16000', '-', 1) |
+---------------------------------------+
| 5000 |
+---------------------------------------+
1 row in set (0.00 sec)
select substring_index('5000-16000-25000', '-', 2);
out:
+---------------------------------------------+
| substring_index('5000-16000-25000', '-', 2) |
+---------------------------------------------+
| 5000-16000 |
+---------------------------------------------+
1 row in set (0.00 sec)
select substring_index('5000-16000-25000', '-', -1);
+----------------------------------------------+
| substring_index('5000-16000-25000', '-', -1) |
+----------------------------------------------+
| 25000 |
+----------------------------------------------+
1 row in set (0.00 sec)
- REPEAT(str,count) – The string repeats as many times as needed
mysql> select repeat('apple', 3);
+--------------------+
| repeat('apple', 3) |
+--------------------+
| appleappleapple |
+--------------------+
1 row in set (0.00 sec)
3.2 Date function
Different DBMS The syntax of the date function varies , This course introduces some standards SQL Recognized can be applied to the vast majority of DBMS Function of . given DBMS You can check the document by using the date function .
- CURRENT_DATE – Get current date
mysql> SELECT CURRENT_DATE;
+--------------+
| CURRENT_DATE |
+--------------+
| 2022-05-25 |
+--------------+
1 row in set (0.00 sec)
- CURRENT_TIME – current time
mysql> select current_time;
+--------------+
| current_time |
+--------------+
| 15:56:01 |
+--------------+
1 row in set (0.00 sec)
- CURRENT_TIMESTAMP – Current date and time
mysql> select current_timestamp;
+---------------------+
| current_timestamp |
+---------------------+
| 2022-05-25 15:56:50 |
+---------------------+
1 row in set (0.00 sec)
- EXTRACT – Intercept date element
grammar :EXTRACT( Date element FROM date )
Use EXTRACT The function can truncate part of the date data , for example “ year ”
“ month ”, perhaps “ Hours ”“ second ” etc. . The return value of this function is not the date type but value type
mysql> SELECT CURRENT_TIMESTAMP as now,
-> EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AS year,
-> EXTRACT(MONTH FROM CURRENT_TIMESTAMP) AS month,
-> EXTRACT(DAY FROM CURRENT_TIMESTAMP) AS day,
-> EXTRACT(HOUR FROM CURRENT_TIMESTAMP) AS hour,
-> EXTRACT(MINUTE FROM CURRENT_TIMESTAMP) AS MINute,
-> EXTRACT(SECOND FROM CURRENT_TIMESTAMP) AS second;
+---------------------+------+-------+------+------+--------+--------+
| now | year | month | day | hour | MINute | second |
+---------------------+------+-------+------+------+--------+--------+
| 2022-05-25 15:59:20 | 2022 | 5 | 25 | 15 | 59 | 20 |
+---------------------+------+-------+------+------+--------+--------+
1 row in set (0.00 sec)
3.3 Conversion function
“ transformation ” The meaning of this word is very broad , stay SQL There are two main meanings in : One is the conversion of data types , It is called type conversion for short , In English, it is called cast; Another layer means the conversion of values .
- CAST – Type conversion
grammar :CAST( The value before conversion AS The data type you want to convert )
mysql> select cast('1944.35' as year);
+-------------------------+
| cast('1944.35' as year) |
+-------------------------+
| 1944 |
+-------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> select CAST('13.56' as SIGNED INTEGER);
+---------------------------------+
| CAST('13.56' as SIGNED INTEGER) |
+---------------------------------+
| 13 |
+---------------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> SELECT CAST('13.56' as float);
+------------------------+
| CAST('13.56' as float) |
+------------------------+
| 13.56 |
+------------------------+
1 row in set (0.00 sec)
-- Convert string type to date type
mysql> SELECT CAST('2009-12-14' AS DATE) AS date_col;
+------------+
| date_col |
+------------+
| 2009-12-14 |
+------------+
1 row in set (0.00 sec)
- COALESCE – take NULL Convert to other values
grammar :COALESCE( data 1, data 2, data 3……)
COALESCE yes SQL Special functions . This function will return variable parameters A Starting from the middle left 1 Not one NULL Value . The number of parameters is variable , Therefore, it can be increased infinitely as needed .
stay SQL In the sentence NULL The conversion function is used when converting to other values .
mysql> SELECT COALESCE(NULL, 11) AS col_1,
-> COALESCE(NULL, 'hello world', NULL) AS col_2,
-> COALESCE(NULL, NULL, '2020-11-01') AS col_3;
+-------+-------------+------------+
| col_1 | col_2 | col_3 |
+-------+-------------+------------+
| 11 | hello world | 2020-11-01 |
+-------+-------------+------------+
1 row in set (0.00 sec)
4. The predicate
A predicate is a function that returns a true value . Include TRUE / FALSE / UNKNOWN.
Predicates mainly include the following :
- LIKE
- BETWEEN
- IS NULL、IS NOT NULL
- IN
- EXISTS
4.1 LIKE The predicate – Partial consistent query for Strings
You need to use this predicate when you need to make a partially consistent query of a string .
Partial consistency can be roughly divided into front consistency 、 There are three types of middle consistency and rear consistency . First, let's create a table :
-- DDL : Create table
CREATE TABLE samplelike(
strcol VARCHAR(6) NOT NULL primary key
);
-- DML : insert data
START TRANSACTION; -- Start business
INSERT INTO samplelike (strcol) VALUES ('abcddd');
INSERT INTO samplelike (strcol) VALUES ('dddabc');
INSERT INTO samplelike (strcol) VALUES ('abdddc');
INSERT INTO samplelike (strcol) VALUES ('abcdd');
INSERT INTO samplelike (strcol) VALUES ('ddabc');
INSERT INTO samplelike (strcol) VALUES ('abddc');
COMMIT; -- Commit transaction
SELECT * FROM samplelike;
+--------+
| strcol |
+--------+
| abcdd |
| abcddd |
| abddc |
| abdddc |
| ddabc |
| dddabc |
+--------+
6 rows in set (0.00 sec)
- The front is consistent : Take out “dddabc”
Consistent in front is the string used as the query condition ( Here is “ddd”) Same as the beginning of the query object string .
SELECT *
FROM samplelike
WHERE strcol LIKE 'ddd%';
+--------+
| strcol |
+--------+
| dddabc |
+--------+
1 row in set (0.00 sec)
mysql>
- The middle is consistent : Take out “abcddd”“dddabc”“abdddc”
Consistent in the middle, that is, the query object string contains the string as the query condition , It doesn't matter whether the string appears at the end or in the middle of the object string .
SELECT *
FROM samplelike
WHERE strcol LIKE '%ddd%';
+--------+
| strcol |
+--------+
| abcddd |
| abdddc |
| dddabc |
+--------+
- The rear is consistent : Take out “abcddd“
The last consistency is the string used as the query condition ( Here is “ddd”) Same as the end of the query object string .
mysql> SELECT *
-> FROM samplelike
-> WHERE strcol LIKE '%ddd';
+--------+
| strcol |
+--------+
| abcddd |
+--------+
1 row in set (0.00 sec)
_Underscores match any 1 Characters
Use _( Underline ) Instead of %, And % The difference is , It represents the “ arbitrarily 1 Characters ”.
SELECT *
FROM samplelike
WHERE strcol LIKE 'abc__';
+--------+
| strcol |
+--------+
| abcdd |
+--------+
1 row in set (0.00 sec)
4.2 BETWEEN The predicate – For range queries
Use BETWEEN You can query the range . This predicate differs from other predicates or functions in that it uses 3 Parameters .
-- Select the sales unit price as 100~ 1000 Yuan goods
SELECT product_name, sale_price
FROM product
WHERE sale_price BETWEEN 100 AND 1000;
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| T T-shirt | 1000 |
| Punch | 500 |
| Fork | 500 |
| Clean the board | 880 |
| Ball pen | 100 |
+--------------+------------+
5 rows in set (0.00 sec)
BETWEEN The characteristic of is that the results will include 100 and 1000 These two critical values , That's the closed interval . If you don't want the results to include critical values , Then you have to use < and >.
SELECT product_name, sale_price
FROM product
WHERE sale_price > 100
AND sale_price < 1000;
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| Punch | 500 |
| Fork | 500 |
| Clean the board | 880 |
+--------------+------------+
3 rows in set (0.00 sec)
4.3 IS NULL、 IS NOT NULL – Used to determine whether it is NULL
In order to select some values as NULL Data of columns , Out of commission =, You can only use specific predicates IS NULL.
SELECT product_name, purchase_price
FROM product
WHERE purchase_price IS NULL;
+--------------+----------------+
| product_name | purchase_price |
+--------------+----------------+
| Fork | NULL |
| Ball pen | NULL |
+--------------+----------------+
2 rows in set (0.00 sec)
On the contrary , Want to choose NULL Data other than , Need to use IS NOT NULL.
SELECT product_name, purchase_price
FROM product
WHERE purchase_price IS NOT NULL;
+--------------+----------------+
| product_name | purchase_price |
+--------------+----------------+
| T T-shirt | 500 |
| Punch | 320 |
| motion T T-shirt | 2800 |
| kitchen knife | 2800 |
| pressure cooker | 5000 |
| Clean the board | 790 |
+--------------+----------------+
6 rows in set (0.00 sec)
4.4 IN The predicate – OR Easy to use
When multiple query criteria are merged, you can choose to use or sentence .
-- adopt OR Specify multiple purchase unit prices to query
SELECT product_name, purchase_price
FROM product
WHERE purchase_price = 320
OR purchase_price = 500
OR purchase_price = 5000;
+--------------+----------------+
| product_name | purchase_price |
+--------------+----------------+
| T T-shirt | 500 |
| Punch | 320 |
| pressure cooker | 5000 |
+--------------+----------------+
3 rows in set (0.00 sec)
Although the above method has no problem , But there are still some shortcomings , That is, as more and more objects want to be selected , SQL The sentence will be longer and longer , It will become more and more difficult to read . At this time , We can use IN The predicate `IN( value 1, value 2, value 3, …) To replace the above SQL sentence .
SELECT product_name, purchase_price
FROM product
WHERE purchase_price IN (320, 500, 5000);
+--------------+----------------+
| product_name | purchase_price |
+--------------+----------------+
| T T-shirt | 500 |
| Punch | 320 |
| pressure cooker | 5000 |
+--------------+----------------+
3 rows in set (0.00 sec)
The above statement is much simpler , Readability is greatly improved . conversely , Hope to pick out “ The purchase unit price is not 320 element 、 500 element 、 5000 element ” When you buy your goods , You can use the negative form NOT IN To achieve .
SELECT product_name, purchase_price
FROM product
WHERE purchase_price NOT IN (320, 500, 5000);
+--------------+----------------+
| product_name | purchase_price |
+--------------+----------------+
| motion T T-shirt | 2800 |
| kitchen knife | 2800 |
| Clean the board | 790 |
+--------------+----------------+
3 rows in set (0.00 sec)
It should be noted that , In the use of IN and NOT IN You can't pick out NULL Data . The actual result is the same , The above two groups of results do not include the purchase unit price of NULL My fork and ball point pen . NULL Only use IS NULL and IS NOT NULL To judge .
4.5 Use subqueries as IN Arguments to predicates
-- DDL : Create table
DROP TABLE IF EXISTS shopproduct;
CREATE TABLE shopproduct(
shop_id CHAR(4) NOT NULL,
shop_name VARCHAR(200) NOT NULL,
product_id CHAR(4) NOT NULL,
quantity INTEGER NOT NULL,
PRIMARY KEY (shop_id, product_id) -- Specify primary key
);
-- DML : insert data
START TRANSACTION; -- Start business
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000A', ' Tokyo ', '0001', 30);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000A', ' Tokyo ', '0002', 50);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000A', ' Tokyo ', '0003', 15);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0002', 30);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0003', 120);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0004', 20);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0006', 10);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0007', 40);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0003', 20);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0004', 50);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0006', 90);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0007', 70);
INSERT INTO shopproduct (shop_id, shop_name, product_id, quantity) VALUES ('000D', ' Fukuoka, ', '0001', 100);
COMMIT; -- Commit transaction
SELECT * FROM shopproduct;
+---------+-----------+------------+----------+
| shop_id | shop_name | product_id | quantity |
+---------+-----------+------------+----------+
| 000A | Tokyo | 0001 | 30 |
| 000A | Tokyo | 0002 | 50 |
| 000A | Tokyo | 0003 | 15 |
| 000B | Nagoya | 0002 | 30 |
| 000B | Nagoya | 0003 | 120 |
| 000B | Nagoya | 0004 | 20 |
| 000B | Nagoya | 0006 | 10 |
| 000B | Nagoya | 0007 | 40 |
| 000C | Osaka | 0003 | 20 |
| 000C | Osaka | 0004 | 50 |
| 000C | Osaka | 0006 | 90 |
| 000C | Osaka | 0007 | 70 |
| 000D | Fukuoka, | 0001 | 100 |
+---------+-----------+------------+----------+
13 rows in set (0.00 sec)
Due to the separate use of store numbers (shop_id) Or item number (product_id) Can't distinguish every row of data in the table , So... Is specified 2 Column as primary key (primary key) Combine stores and goods , Used to uniquely identify each row of data .
Suppose we need to take out the sales unit price of goods on sale in Osaka , How to achieve it ?
First step , Take out the goods on sale in Osaka store product_id ;
The second step , Take out the sales unit price of goods on sale in Osaka stores sale_price
-- step1: Take out the goods on sale in Osaka store `product_id`
SELECT product_id
FROM shopproduct
WHERE shop_id = '000C';
+------------+
| product_id |
+------------+
| 0003 |
| 0004 |
| 0006 |
| 0007 |
+------------+
4 rows in set (0.00 sec)
Subqueries are executed from the innermost layer ( From the inside out ), therefore , After the subquery of the above statement is executed ,sql Expand into the following statement .
-- The expanded result of subquery
SELECT product_name, sale_price
FROM product
WHERE product_id IN ('0003', '0004', '0006', '0007');
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| motion T T-shirt | 4000 |
| kitchen knife | 3000 |
| Fork | 500 |
| Clean the board | 880 |
+--------------+------------+
4 rows in set (0.00 sec)
You can see , After the subquery is transformed, it becomes in Predicate usage , Do you understand ? perhaps , You'll wonder if in Predicates can also implement , So why use subqueries ? Here are two reasons :
①: In real life , The goods on sale in a store are constantly changing , Use in Predicates need to be updated frequently sql sentence , Reduced efficiency , Increased maintenance costs ;
②: actually , There may be hundreds of goods on sale in a store , It's a big project to manually maintain the item number on sale .
Use subqueries to keep sql The statement remains unchanged , It greatly improves the maintainability of the program , This is a key consideration in system development .
- NOT IN And subquery
NOT IN Subqueries are also supported as parameters , Usage and in Exactly the same as .
-- NOT IN Use subqueries as parameters , Take out the sales unit price of goods not sold in Tokyo stores
SELECT product_name, sale_price
FROM product
WHERE product_id NOT IN (SELECT product_id
FROM shopproduct
WHERE shop_id = '000A');
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| kitchen knife | 3000 |
| pressure cooker | 6800 |
| Fork | 500 |
| Clean the board | 880 |
| Ball pen | 100 |
+--------------+------------+
5 rows in set (0.00 sec)
4.6 EXIST The predicate
EXIST The use of predicates is difficult to understand .
① EXIST The method of using is different from that before
② Grammar is difficult to understand
③ In fact, even if you don't use EXIST, Basically, you can also use IN( perhaps NOT IN) Instead of
So to speak , And learning EXIST Is predicate necessary ? The answer is yes , Because once you can skillfully use EXIST The predicate , You can realize its great convenience .
however , You don't have to worry too much , This course introduces some basic usage , When you study in the future, you can pay more attention to EXIST The use of predicates , With a view to reaching SQL Master this usage at intermediate level .
- EXIST How to use predicates
The function of predicate is “ Determine whether there are records that meet certain conditions ”.
If such a record exists, it returns true (TRUE), If it does not exist, return false (FALSE).
EXIST( There is ) The subject of the predicate is “ Record ”.
We continue to IN And subquery Example in , Use EXIST Select the sales unit price of goods on sale in Osaka stores .
SELECT product_name, sale_price
FROM product AS p
WHERE EXISTS (SELECT *
FROM shopproduct AS sp
WHERE sp.shop_id = '000C'
AND sp.product_id = p.product_id);
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| motion T T-shirt | 4000 |
| kitchen knife | 3000 |
| Fork | 500 |
| Clean the board | 880 |
+--------------+------------+
4 rows in set (0.00 sec)
- EXIST Parameters of
The predicate we learned before , It's basically like “ Column LIKE character string ” perhaps “ Column BETWEEN value 1 AND value 2” This requires specifying 2 More than parameters , and EXIST There are no parameters on the left side of the . because EXIST It's just 1 A predicate with two parameters . therefore ,EXIST Just write on the right 1 Parameters , This parameter will usually be a subquery .
(SELECT 1
FROM shopproduct AS sp
WHERE sp.shop_id = '000C'
AND sp.product_id = p.product_id)
The subquery above is the only parameter . To be precise , Due to the passing conditions “SP.product_id = P.product_id” take product Table and shopproduct Tables are joined , Therefore, as a parameter, the associated subquery . EXIST Associated subqueries are usually used as parameters .
- In subquery SELECT *
because EXIST Only care about whether records exist , Therefore, it doesn't matter which columns are returned . EXIST It will only judge whether there is a sub query that satisfies WHERE Clause “ Store number (shop_id) by ‘000C’, goods (product) Watches and shops
goods (shopproduct) Item number in the table (product_id) identical ” The record of , True is returned only if such a record exists (TRUE).
therefore , Use the following query statement , The query results will not change .
SELECT product_name, sale_price
FROM product AS p
WHERE EXISTS (SELECT 1 -- The appropriate constants can be written here
FROM shopproduct AS sp
WHERE sp.shop_id = '000C'
AND sp.product_id = p.product_id);
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| motion T T-shirt | 4000 |
| kitchen knife | 3000 |
| Fork | 500 |
| Clean the board | 880 |
+--------------+------------+
4 rows in set (0.00 sec)
You can put in EXIST Write in the subquery of SELECT * As SQL A habit of .
- Use NOT EXIST Replace NOT IN
It's like EXIST Can be substituted for IN equally , NOT IN It can also be used. NOT EXIST To replace .
The following code example takes out , Sales unit price of goods not sold in Tokyo stores .
SELECT product_name, sale_price
FROM product AS p
WHERE NOT EXISTS (SELECT *
FROM shopproduct AS sp
WHERE sp.shop_id = '000A'
AND sp.product_id = p.product_id);
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| kitchen knife | 3000 |
| pressure cooker | 6800 |
| Fork | 500 |
| Clean the board | 880 |
| Ball pen | 100 |
+--------------+------------+
5 rows in set (0.00 sec)
NOT EXIST And EXIST contrary , When “ non-existent ” Returns true when records that meet the conditions specified in the subquery (TRUE).
5. CASE expression
CASE An expression is a kind of function . yes SQL One of the most important functions in , It is necessary to study hard .
CASE Expressions are used to distinguish situations , This distinction is commonly referred to in programming as ( Conditions ) Branch .
CASE The syntax of expressions is divided into simple CASE Expressions and searches CASE There are two kinds of expressions . Because of the search CASE The expression contains simple CASE All the functions of expressions . This course will focus on searching CASE expression .
grammar :
CASE WHEN < Evaluation expression > THEN < expression >
WHEN < Evaluation expression > THEN < expression >
WHEN < Evaluation expression > THEN < expression >
.
.
.
ELSE < expression >
END
When the above statement is executed , Judge in turn when Whether the expression is true , Yes, it is THEN The following sentence , If all when All expressions are false , execute ELSE The following sentence . No matter how huge CASE expression , Finally, only one value will be returned .
5.1 CASE How to use expressions
Suppose now To achieve the following results :
A : clothes
B : Office Supplies
C : Kitchenware
Because the records in the table do not contain “A : ” perhaps “B : ” Such a string , So you need to be in SQL Add . And will “A : ”“B : ”“C : ” Combined with records .
- Application scenarios 1: Get different column values according to different branches
SELECT product_name,
CASE WHEN product_type = ' clothes ' THEN CONCAT('A : ',product_type)
WHEN product_type = ' Office Supplies ' THEN CONCAT('B : ',product_type)
WHEN product_type = ' Kitchenware ' THEN CONCAT('C : ',product_type)
ELSE NULL
END AS abc_product_type
FROM product;
+--------------+------------------+
| product_name | abc_product_type |
+--------------+------------------+
| T T-shirt | A : clothes |
| Punch | B : Office Supplies |
| motion T T-shirt | A : clothes |
| kitchen knife | C : Kitchenware |
| pressure cooker | C : Kitchenware |
| Fork | C : Kitchenware |
| Clean the board | C : Kitchenware |
| Ball pen | B : Office Supplies |
+--------------+------------------+
8 rows in set (0.00 sec)
ELSE Clauses can also be omitted without writing , It will be defaulted to ELSE NULL. But to prevent someone from missing , I still hope you can explicitly write ELSE Clause . Besides , CASE At the end of the expression “END” It can't be omitted , Please pay special attention not to miss . Forget to write END There will be grammatical errors , This is also the easiest mistake to make at the beginning of learning .
- Application scenarios 2: Achieve aggregation in the column direction
Usually we use the following code to implement different kinds of aggregation in the direction of lines ( Here is sum).
SELECT product_type,
SUM(sale_price) AS sum_price
FROM product
GROUP BY product_type;
+--------------+-----------+
| product_type | sum_price |
+--------------+-----------+
| clothes | 5000 |
| Office Supplies | 5500 |
| Kitchenware | 11180 |
If you want to display different kinds of aggregate values in the direction of the column , How to write ?
+-------------------+-------------------+------------------+
| sum_price_clothes | sum_price_kitchen | sum_price_office |
+-------------------+-------------------+------------------+
| 5000 | 5500 | 11180 |
+-------------------+-------------------+------------------+
1 row in set (0.00 sec)
-- Using aggregate functions + case ... when That is to say
select sum(case product_type
when ' clothes ' then sale_price
else 0
end) as sum_price_clothes,
sum(case product_type
when ' Office Supplies ' then sale_price
else 0
end) sum_price_kitchen,
sum(case product_type
when ' Kitchenware ' then sale_price
else 0
end) sum_price_office
from product;
5.2 Realize row to column conversion
There is one score surface , as follows :
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
`id` int(10) PRIMARY KEY AUTO_INCREMENT COMMENT 'ID',
`name` varchar(22) DEFAULT '' COMMENT ' full name ',
`subject` VARCHAR(20) COMMENT ' subject ',
`grade` INTEGER COMMENT ' achievement '
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `score`(name, subject, grade) VALUES
(' Zhang San ', 'chinese', 93),
(' Zhang San ', 'math', 88),
(' Zhang San ', 'English', 91);
INSERT INTO `score`(name, subject, grade) VALUES
(' Li Si ', 'chinese', 87),
(' Li Si ', 'math', 90),
(' Li Si ', 'English', 77);
select * from score;
+----+------+---------+-------+
| id | name | subject | grade |
+----+------+---------+-------+
| 1 | Zhang San | chinese | 93 |
| 2 | Zhang San | math | 88 |
| 3 | Zhang San | English | 91 |
| 4 | Li Si | chinese | 87 |
| 5 | Li Si | math | 90 |
| 6 | Li Si | English | 77 |
+----+------+---------+-------+
6 rows in set (0.00 sec)
Please interchange the lines , The programming is in the following form :
+------+---------+------+---------+
| name | chinese | math | english |
+------+---------+------+---------+
| Zhang San | 93 | 88 | 91 |
| Li Si | 87 | 90 | 77 |
+------+---------+------+---------+
2 rows in set (0.00 sec)
as follows :
-- CASE WHEN Implement a digital column grade Transfer line column
SELECT
`name`,
sum(CASE WHEN SUBJECT = 'chinese' THEN grade ELSE grade = 0 END ) AS chinese,
sum( CASE WHEN SUBJECT = 'math' THEN grade ELSE grade = 0 END ) AS math,
sum(
CASE
WHEN SUBJECT = 'English' THEN
grade
ELSE
grade = 0
END
) AS English
FROM
score
GROUP BY
NAME
The above code implements the number column score Row column of , You can also implement text columns subject Row column of
-- CASE WHEN Implement a digital column subject Transfer line column
mysql> SELECT
-> `name`,
-> max(CASE WHEN SUBJECT = 'chinese' THEN subject else NULL END ) AS chinese,
-> max( CASE WHEN SUBJECT = 'math' THEN subject ELSE null END ) AS math,
-> max(
-> CASE
-> WHEN SUBJECT = 'English' THEN
-> subject
-> ELSE
-> null
-> END
-> ) AS English
-> FROM
-> score
-> GROUP BY
-> NAME
-> ;
+------+---------+------+---------+
| name | chinese | math | English |
+------+---------+------+---------+
| Zhang San | chinese | math | English |
| Li Si | chinese | math | English |
+------+---------+------+---------+
2 rows in set (0.00 sec)
mysql>
summary :
- When the column to be converted is a number , have access to
SUM AVG MAX MINWait for the aggregate function ; - When the column to be converted is text , have access to
MAX MINWait for the aggregate function
5.3 Exercises
- Judgment questions
The four operations contain NULL when ( Without special treatment ), Whether the result of the operation must become NULL ?
Yes . Test the following :
mysql> select purchase_price *10 from product where product_id = 0008;
+--------------------+
| purchase_price *10 |
+--------------------+
| NULL |
+--------------------+
1 row in set (0.00 sec)
mysql> select purchase_price *10 + 5 from product where product_id = 0008;
+------------------------+
| purchase_price *10 + 5 |
+------------------------+
| NULL |
+------------------------+
1 row in set (0.00 sec)
- As used in this chapter
product( goods ) The table is executed as follows 2 stripSELECTsentence , What kind of results can we get ?
SELECT product_name, purchase_price
FROM product
WHERE purchase_price NOT IN (500, 2800, 5000);
-- IN I won't support it select NULL Value
SELECT product_name, purchase_price
FROM product
WHERE purchase_price NOT IN (500, 2800, 5000, NULL);
mysql> SELECT product_name, purchase_price
-> FROM product
-> WHERE purchase_price NOT IN (500, 2800, 5000);
+--------------+----------------+
| product_name | purchase_price |
+--------------+----------------+
| Punch | 320 |
| Clean the board | 790 |
+--------------+----------------+
2 rows in set (0.00 sec)
mysql> SELECT product_name, purchase_price
-> FROM product
-> WHERE purchase_price NOT IN (500, 2800, 5000, NULL);
Empty set (0.00 sec)
mysql> select * from product;
+------------+--------------+--------------+------------+----------------+-------------+
| product_id | product_name | product_type | sale_price | purchase_price | regist_date |
+------------+--------------+--------------+------------+----------------+-------------+
| 0001 | T shirt | clothes | 1000 | 500 | 2009-09-20 |
| 0002 | Punch | Office Supplies | 500 | 320 | 2009-09-11 |
| 0003 | motion T T-shirt | clothes | 4000 | 2800 | NULL |
| 0004 | kitchen knife | Kitchenware | 3000 | 2800 | 2009-09-20 |
| 0005 | pressure cooker | Kitchenware | 6800 | 5000 | 2009-01-15 |
| 0006 | Fork | Kitchenware | 500 | NULL | 2009-09-20 |
| 0007 | Clean the board | Kitchenware | 880 | 790 | 2008-04-28 |
| 0008 | Ball pen | Office Supplies | 5000 | NULL | 2009-11-11 |
+------------+--------------+--------------+------------+----------------+-------------+
8 rows in set (0.00 sec)
IN keyword , Rows that cannot be filtered . If IN in Yes NULL Then the results are NULL.
- According to the sales unit price (
sale_price) Yes, practice 3.6 Mediumproduct( goods ) The goods in the table are classified as follows .
- Low end goods : The sales unit price is in 1000 Yen ( contain 1000) following (T shirt 、 Office Supplies 、 Fork 、 Clean the board 、 Ball pen )
- Mid range goods : The sales unit price is in 1000 Above JPY 3000 Below yen ( contain 3000)( kitchen knife )
- High end goods : The sales unit price is in 3000 Above JPY ( motion T T-shirt 、 pressure cooker )
Please write down the statistics of the number of goods included in the above categories SELECT sentence , The results are shown below .
Execution results :
+-----------+--------------+------------+
| low_price | middle_price | high_price |
+-----------+--------------+------------+
| 4 | 1 | 3 |
+-----------+---------
mysql> select * from product;
+------------+--------------+--------------+------------+----------------+-------------+
| product_id | product_name | product_type | sale_price | purchase_price | regist_date |
+------------+--------------+--------------+------------+----------------+-------------+
| 0001 | T shirt | clothes | 1000 | 500 | 2009-09-20 |
| 0002 | Punch | Office Supplies | 500 | 320 | 2009-09-11 |
| 0003 | motion T T-shirt | clothes | 4000 | 2800 | NULL |
| 0004 | kitchen knife | Kitchenware | 3000 | 2800 | 2009-09-20 |
| 0005 | pressure cooker | Kitchenware | 6800 | 5000 | 2009-01-15 |
| 0006 | Fork | Kitchenware | 500 | NULL | 2009-09-20 |
| 0007 | Clean the board | Kitchenware | 880 | 790 | 2008-04-28 |
| 0008 | Ball pen | Office Supplies | 5000 | NULL | 2009-11-11 |
+------------+--------------+--------------+------------+----------------+-------------+
8 rows in set (0.00 sec)
select sum(case when sale_price <= 1000 then sale_price = 1 else sale_price = 0 end) low_price -- sale_price = 1 : It's wrong.
from product;
-- SQL sentence
select sum(case when sale_price <= 1000 then 1 else 0 end) low_price,
sum(case when sale_price > 1000 and sale_price <= 3000 then 1 else 0 end) middle_price,
sum(case when sale_price > 3000 then 1 else 0 end) high_price
from product;
+-----------+--------------+------------+
| low_price | middle_price | high_price |
+-----------+--------------+------------+
| 4 | 1 | 3 |
+-----------+--------------+------------+
1 row in set (0.00 sec)
mysql>
边栏推荐
- Basic use of WinForm programming control treeview tree view 20220527
- spider pi 智能视觉六足机器人 巡路功能 0603
- Spider PI intelligent vision hexapod robot color recognition function 0603
- datagridview的基本使用 0526
- PostgreSQL近期常用的表结构查询语句
- PostgreSQL recently Common Table structure Query statements
- Deep learning and CV tutorial (13) | target detection (SSD, Yolo Series)
- How to make our self built site have a custom domain name (1)
- 与鲲鹏代码迁移工具的初次邂逅
- Matlab implementation of Pettitt mutation test
猜你喜欢

Scratch Programming flying birds Development Notes 0604

scratch编程 飞翔的小鸟 开发笔记 0604

Matlab implementation of Pettitt mutation test

Modbus protocol and serialport port read / write

Audio 3A processing practice makes your application more "pleasant"

Huawei cloud zero code development image compression tool

Implementation principle and best practice of big data ecological security framework (Part I)

Yolo series target detection post-processing - non maximum suppression

List of resources of yimai.com development interest buying project 0605

Load balancing configuration of EIGRP for daily technology sharing
随机推荐
基础查询语句
Second cloud cloud's original fully compatible solution for information innovation promotes the acceleration of the implementation of information innovation industry
校园锐捷路由器使用指南
Sqlserver2012 does not allow to modify the table structure 0607
化工企业双重预防体系数字化综合管理系统
Browser from download to rendering
202206007 模拟赛 总结
spider pi 智能视觉六足机器人 巡路功能 0603
Ble link layer air packet format
Scratch Programming flying birds Development Notes 0604
Learning records of thread pool
邦纳光电开关SM912LVQD
Huawei cloud zero code development image compression tool
Spider PI intelligent vision hexapod robot in direct connection mode 0603
2022安全生产月活动启动安全生产与疫情防控两手抓
工业互联网+危化安全生产数字化综合管理云平台
Database SQL and Gorm practice of design pattern | notes on youth training camp
datagridview的基本使用 0526
健身是什么?
St link V2 Download: internal command error & error: flash download failed - target DLL has been canceled