当前位置:网站首页>MySQL learning record (7)
MySQL learning record (7)
2022-07-02 21:30:00 【White_ Silence (Learning version)】
1. function
1.1 classification
- 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 )
1.1.1 Arithmetic functions
-- First create a table to demonstrate
-- DDL : Create table
USE shop;
DROP TABLE IF EXISTS samplemath;
CREATE TABLE samplemath
(m float(10,3),
n INT,
p INT);
-- DML : insert data
START TRANSACTION; -- Start business
INSERT INTO samplemath(m, n, p) VALUES (500, 0, NULL);
INSERT INTO samplemath(m, n, p) VALUES (-180, 0, NULL);
INSERT INTO samplemath(m, n, p) VALUES (NULL, NULL, NULL);
INSERT INTO samplemath(m, n, p) VALUES (NULL, 7, 3);
INSERT INTO samplemath(m, n, p) VALUES (NULL, 5, 2);
INSERT INTO samplemath(m, n, p) VALUES (NULL, 4, NULL);
INSERT INTO samplemath(m, n, p) VALUES (8, NULL, 3);
INSERT INTO samplemath(m, n, p) VALUES (2.27, 1, NULL);
INSERT INTO samplemath(m, n, p) VALUES (5.555,2, NULL);
INSERT INTO samplemath(m, n, p) VALUES (NULL, 1, NULL);
INSERT INTO samplemath(m, n, p) VALUES (8.76, NULL, NULL);
COMMIT; -- Commit transaction
-- Query table content
SELECT * FROM samplemath;
+----------+------+------+
| 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 (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
.
- 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 .
- 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
select * from samplemath;
SELECT m, ABS(m) AS abs_col,
n,p, MOD(n,p) AS mod_col,
ROUND(m,1) AS round_col
FROM samplemath;
1.1.2 String function
- CONCAT – Splicing
grammar :CONCAT(str1, str2, str3)
MySQL Use in CONCAT Function .
- LENGTH – String length
grammar :LENGTH( character string )
- 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 .
- REPLACE – String replacement
grammar :REPLACE( Object string , String before replacement , Replaced string )
- SUBSTRING – String truncation
grammar :SUBSTRING ( Object string FROM Intercept start position FOR Number of characters intercepted )
Use SUBSTRING 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.
- SUBSTRING_INDEX – 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.
-- 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);
INSERT INTO samplestr (str1, str2, str3) VALUES ('abc', 'def', NULL);
INSERT INTO samplestr (str1, str2, str3) VALUES (' The sun ', ' The moon ', ' Mars ');
INSERT INTO samplestr (str1, str2, str3) VALUES ('aaa', NULL, NULL);
INSERT INTO samplestr (str1, str2, str3) VALUES (NULL, 'xyz', NULL);
INSERT INTO samplestr (str1, str2, str3) VALUES ('@!#$%', NULL, NULL);
INSERT INTO samplestr (str1, str2, str3) VALUES ('ABC', NULL, NULL);
INSERT INTO samplestr (str1, str2, str3) VALUES ('aBC', NULL, NULL);
INSERT INTO samplestr (str1, str2, str3) VALUES ('abc ha-ha ', 'abc', 'ABC');
INSERT INTO samplestr (str1, str2, str3) VALUES ('abcdefabc', 'abc', 'ABC');
INSERT INTO samplestr (str1, str2, str3) VALUES ('micmic', 'i', 'I');
COMMIT;
-- Confirm the contents in the table
SELECT * FROM samplestr;
select *,CONCAT(str1,str2,str3) AS str_concat, length(str1) as str_len,lower(str1)as str_low,
replace(str1,str2,str3)as rep_str,substring(str1 from 3 for 2)as sub_str
from samplestr;
ps:replace In is the object string ( Parameters 1) And the string before replacement ( Parameters 2) Replace the same part with the replaced string ( Parameters 3) The corresponding content in .
1.1.3 Date function
- CURRENT_DATE – Get current date
- CURRENT_TIME – current time
- CURRENT_TIMESTAMP – Current date and time
- 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 a date type, but a numeric type
SELECT CURRENY_DATE;
SELECT CURRENT_TIME;
SELECT CURRENT_TIMESTAMP;
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;
-- There should be no space between the function and the following parentheses , Otherwise, it will report a mistake
--EXTRACT There should be no space between the function and the following parentheses , Otherwise, it will report a mistake .
1.1.4 Conversion function
- CAST – Type conversion
grammar :CAST( The value before conversion AS The data type you want to convert )
-- Convert string type to numeric type
SELECT CAST('0001' AS SIGNED INTEGER) AS int_col;
-- Convert string type to date type
SELECT CAST('2009-12-14' AS DATE) AS date_col;
- 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 .
SELECT COALESCE(NULL, 11) AS col_1,
COALESCE(NULL, 'hello world', NULL) AS col_2,
COALESCE(NULL, NULL, '2020-11-01') AS col_3;
2. The predicate
The predicate : 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
2.1 LIKE The predicate – Partial consistent query for Strings
Partial consistency can be roughly divided into front consistency 、 There are three types of middle consistency and rear consistency .
% The function of is similar to wildcard
_
Underscores match any 1 Characters
Use _( Underline ) Instead of %, And % The difference is , It represents the “ arbitrarily 1 Characters ”.
-- DDL : Create table
CREATE TABLE samplelike
( strcol VARCHAR(6) NOT NULL,
PRIMARY KEY (strcol)
samplelike);
-- 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;
-- The front is consistent
SELECT *
FROM samplelike
WHERE strcol like 'ddd%';
-- The middle is consistent
SELECT *
FROM samplelike
WHERE strcol like '%ddd%';
-- The rear is consistent
SELECT *
FROM samplelike
WHERE strcol like "%ddd";
SELECT *
FROM samplelike
WHERE strcol like 'abc_';
2.2 BETWEEN The predicate – For range queries
Use BETWEEN You can query the range ,BETWEEN Used 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;
BETWEEN The characteristic of is that the results will include 100 and 1000 These two critical values , That is to say Closed interval . If you don't want the results to include critical values , Then you have to use < and >.
2.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.
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 NULL;
SELECT product_name, purchase_price
FROM product
WHERE purchase_price IS NOT NULL;
2.4 IN The predicate – OR Easy to use
The union of multiple query conditions 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;
-- Instead of using IN
SELECT product_name, purchase_price
FROM product
WHERE purchase_price IN (320, 500, 5000);
It should be noted that , In the use of IN and NOT IN You can't pick out NULL Data .
2.5 Use subqueries as IN Arguments to predicates
- IN /NOT IN And subquery
IN The predicate (NOT IN The predicate ) Has a usage that other predicates do not have , You can use a subquery as its parameter , Views can also be used as IN Parameters of .
-- 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 product_name, sale_price
FROM product
WHERE product_id IN (SELECT product_id
FROM shopproduct
WHERE shop_id = '000C');
-- The expanded result of subquery
SELECT product_name, sale_price
FROM product
WHERE product_id IN ('0003', '0004', '0006', '0007');
-- NOT IN Use subqueries as parameters , Take out the sales unit price of goods not sold in Osaka stores
SELECT product_name, sale_price
FROM product
WHERE product_id NOT IN (SELECT product_id
FROM shopproduct
WHERE shop_id = '000A');
2.6 EXISTS/ NOT EXISTS The predicate
- EXISTS 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).
EXISTS( There is ) The subject of the predicate is “ Record ”.
EXISTS There is only one , Write casually .
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);
3. CASE expression
CASE Expressions are used to distinguish situations , This distinction is commonly referred to in programming as ( Conditions ) Branch .
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 .
-- 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;
--
-- Application scenarios 2: Achieve aggregation in the column direction
-- Perform line to line conversion on the total sales unit price calculated by commodity type
SELECT SUM(CASE WHEN product_type = ' clothes ' THEN sale_price ELSE 0 END) AS sum_price_clothes,
SUM(CASE WHEN product_type = ' Kitchenware ' THEN sale_price ELSE 0 END) AS sum_price_kitchen,
SUM(CASE WHEN product_type = ' Office Supplies ' THEN sale_price ELSE 0 END) AS sum_price_office
FROM product;
-- Application scenarios 3: Realize row to column conversion
-- CASE WHEN Implement a digital column score Transfer line column
SELECT name,
SUM(CASE WHEN subject = ' Chinese language and literature ' THEN score ELSE null END) as chinese,
SUM(CASE WHEN subject = ' mathematics ' THEN score ELSE null END) as math,
SUM(CASE WHEN subject = ' Foreign Languages ' THEN score ELSE null END) as english
FROM score
GROUP BY name;
-- CASE WHEN Implement text column subject Transfer line column
SELECT name,
MAX(CASE WHEN subject = ' Chinese language and literature ' THEN subject ELSE null END) as chinese,
MAX(CASE WHEN subject = ' mathematics ' THEN subject ELSE null END) as math,
MIN(CASE WHEN subject = ' Foreign Languages ' THEN subject ELSE null END) as english
FROM score
GROUP BY name;
- When the column to be converted is a number , have access to
SUM AVG MAX MIN
Wait for the aggregate function ; - When the column to be converted is text , have access to
MAX MIN
Wait for the aggregate function
Exercises :
According to the sales unit price ( sale_price) Yes, practice 6.1 Medium product( goods ) The goods in the table are classified as follows .
- Low end goods : The sales unit price is in 1000 Below yen (T shirt 、 Office Supplies 、 Fork 、 Clean the board 、 Ball pen )
- Mid range goods : The sales unit price is in 1001 Above JPY 3000 Below yen ( kitchen knife )
- High end goods : The sales unit price is in 3001 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 .
SELECT COUNT(CASE WHEN sale_price <=1000 THEN product_name ELSE null END) AS low_price,
COUNT(CASE WHEN sale_price >1000 AND sale_price <=3000 THEN product_name ELSE null END) AS mid_price,
COUNT(CASE WHEN sale_price >3000 THEN product_name ELSE null END) AS high_price
from product;
Alibaba cloud Tianchi tutorial .
边栏推荐
- Redis -- three special data types
- Add two numbers of leetcode
- Construction and maintenance of business websites [9]
- Research Report on plastic antioxidant industry - market status analysis and development prospect forecast
- Research Report on micro gripper industry - market status analysis and development prospect prediction
- Activation function - relu vs sigmoid
- Research Report on ranking analysis and investment strategic planning of RFID market competitiveness of China's industrial manufacturing 2022-2028 Edition
- JDBC | Chapter 3: SQL precompile and anti injection crud operation
- [hands on deep learning]02 softmax regression
- Accounting regulations and professional ethics [17]
猜你喜欢
How does esrally perform simple custom performance tests?
qwb2018_ core kernel_ rop
Add two numbers of leetcode
[hands on deep learning]02 softmax regression
One week dynamics of dragon lizard community | 2.07-2.13
I drew a Gu ailing with characters!
treevalue——Master Nested Data Like Tensor
[shutter] shutter layout component (opacity component | clipprect component | padding component)
7. Build native development environment
26 FPS video super-resolution model DAP! Output 720p Video Online
随机推荐
Structured text language XML
Plastic granule Industry Research Report - market status analysis and development prospect forecast
Today, I met a Alipay and took out 35K. It's really sandpaper to wipe my ass. it's a show for me
Research Report on the overall scale, major manufacturers, major regions, products and applications of metal oxide arresters in the global market in 2022
Internet Explorer ignores cookies on some domains (cannot read or set cookies)
I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
Roommate, a king of time, I took care of the C language structure memory alignment
股票开户要找谁?手机开户是安全么?
Accounting regulations and professional ethics [19]
Research Report on market supply and demand and strategy of China's Plastic Geogrid industry
China's log saw blade market trend report, technological innovation and market forecast
Import a large amount of data to redis in shell mode
Number of DP schemes
Research Report on market supply and demand and strategy of China's right-hand outward rotation entry door industry
Basic knowledge of tree and binary tree (detailed illustration)
[shutter] statefulwidget component (image component | textfield component)
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of shock absorber oil in the global market in 2022
[CV] Wu Enda machine learning course notes | Chapter 12
Huawei Hongmeng watch achieves fireworks display effect on New Year's Eve
Construction and maintenance of business websites [10]