当前位置:网站首页>SQL learning (2) -- basic query and sorting of tables
SQL learning (2) -- basic query and sorting of tables
2022-07-27 01:12:00 【Although Beihai is on credit, Fuyao can take it】
Here's the catalog title
Link to the original text 1:https://github.com/datawhalechina/wonderful-sql
Link to the original text 2:https://gitee.com/datawhalechina/wonderful-sql
Video link :https://www.bilibili.com/video/BV1pZ4y117W3/?spm_id_from=333.788&vd_source=7f8a29f8895e96fac156aef0574baa6a
1、 Data query
1.1、 Query data
- SELECT sentence
** Inquire about :** When selecting data from a table, you need to use SELECT sentence , That is, only from the list (SELECT) Meaning of necessary data .
basic SELECT The statement contains SELECT and FROM Two clauses (clause). Examples are as follows :
SELECT < Name > FROM < Table name >;
among ,SELECT Clause lists the names of the columns you want to query from the table , and FROM Clause specifies the name of the table from which the data is selected .
1.2、 Filter query
- WHERE sentence
When you don't need to take out all the data , But when selecting data that meets certain conditions , Use WHERE sentence .
SELECT Statement passing WHERE Clause to specify the conditions for querying data .
stay WHERE Clause can specify “ The value of a column is equal to this string ” perhaps “ The value of a column is greater than this number ” Equal conditions . Execute... With these conditions SELECT sentence , You can query only the records that meet this condition .
-- grammar
SELECT < Name >, ……
FROM < Table name >
WHERE < Conditional expression >;
-- Used to select product type As a record of clothes SELECT sentence
SELECT product_name, product_type
FROM product
WHERE product_type = ' clothes ';
1.3、 remarks
- asterisk (*) Stands for all columns .
- SQL You can use line breaks at will in , Does not affect statement execution ( But don't insert a blank line ).
- You need to use double quotation marks when setting Chinese alias (" ") Cover up .
- stay SELECT Use in statement DISTINCT You can delete duplicate lines .
- Comments are SQL The part of a statement used to identify instructions or precautions . It is divided into 1 Line notes "–“ And multiline comments ”/* */".
-- When you want to query all columns , You can use asterisks representing all columns (*).
SELECT * FROM < Table name >;
-- SQL Statement can be used AS Keyword to alias a column ( Double quotation marks are required when using Chinese (" ")).
SELECT product_id As id,
product_name As name,
purchase_price AS " Purchase unit price "
FROM product;
SELECT product_type
FROM productions;

-- Use DISTINCT Delete product_type Duplicate data in column
SELECT DISTINCT product_type
FROM product;

2、 Operator
2.1、 Arithmetic operator
| meaning | Operator |
|---|---|
| Add | + |
| Subtraction | - |
| Multiplication | * |
| division | / |
Higher order mathematical operations Refer to arithmetic function :http://t.csdn.cn/odqEo (3.1 section )
2.2、 Comparison operator

Note that it does not mean :<>
2.3、 Logical operators
| meaning | Operator |
|---|---|
| And | and |
| or | or |
| Not | not |
| priority : not > and > or | |
| AND Operator takes precedence over OR Operator , Want to give priority to OR operation , Brackets can be used |
2.3.1、 Compound operation
- AND Returns true when the true values on both sides of the operator are true , In addition, all return false .
- OR As long as one of the true values on both sides of the operator is not false, it returns true , False is returned only if the true values on both sides are false .
- NOT The operator simply converts true to false , Convert false to true .
2.3.2、 contain NULL Value compound operation
contain NULL True value at
NULL The truth result of is neither true , It's not false , Because I don't know such a value .
At this time, the true value is the third value besides true and false —— Not sure (UNKNOWN). This third value does not exist in general logical operations .SQL Other languages basically use only true and false truth values . In contrast to the usual logical operation called binary logic , Only SQL The logical operation in is called ternary logic .
Three valued logic AND and OR The truth table is :
2.4、 remarks
- SELECT、WHERE You can use constants or expressions in clauses .
-- SQL You can also use operational expressions in statements
SELECT product_name, sale_price, sale_price * 2 AS "sale_price x2"
FROM product;
-- WHERE Clause can also be used in conditional expressions
SELECT product_name, sale_price, purchase_price
FROM product
WHERE sale_price - purchase_price >= 500;
In principle, data of string type Sort in dictionary order , It can't be confused with the size order of numbers .
Hope to choose NULL When recording , You need to use... In conditional expressions IS NULL Operator . I hope the choice is not NULL When recording , You need to use... In conditional expressions IS NOT NULL Operator .
-- selection NULL The record of
SELECT product_name, purchase_price
FROM product
WHERE purchase_price IS NULL;
-- Select not NULL The record of
SELECT product_name, purchase_price
FROM product
WHERE purchase_price IS NOT NULL;
3、 Aggregate query ( Aggregate functions )
SQL The function used for aggregation in is called aggregate function . The following five are the most commonly used aggregate functions :
- COUNT: Count the number of records in the table ( Row number )
- SUM: Calculate the total value of the data in the numerical column of the table
- AVG: Calculate the average value of the data in the numerical column in the table
- MAX: Find the maximum value of the data in any column of the table
- MIN: Find the minimum value of data in any column in the table
-- grammar
COUNT(*)
SUM(sale_price)
AVG(sale_price)
MAX(regist_date)
MIN(regist_date)
remarks :
- COUNT The result of the function varies according to the parameters .COUNT(*) It will contain NULL The number of rows of data , and COUNT(< Name >) You'll get NULL Number of rows of data outside .
- The aggregate function will NULL Ruled out . but COUNT(*) exception , Does not rule out NULL.
- MAX/MIN Functions are almost applicable to All data types The column of .SUM/AVG function Applies only to numeric types The column of .
- When you want to calculate the type of value , Can be in COUNT In the parameters of the function DISTINCT. Use... In the arguments of aggregate functions DISTINCT, Duplicate data can be removed .
4、 Group query
4.1、GROUP BY sentence
Aggregate functions Will process the data of the entire table ,
GROUP BY The existing data can be summarized and counted according to a certain column
stay GROUP BY The column specified in the clause is called Polymerization bond perhaps Group columns .
-- grammar
SELECT < Name 1>,< Name 2>, < Name 3>, ……
FROM < Table name >
GROUP BY < Name 1>, < Name 2>, < Name 3>, ……;
-- Count the number of rows of data by commodity category
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type;

- The aggregate key contains NULL when
Will NULL As a special set of data
SELECT purchase_price, COUNT(*)
FROM product
GROUP BY purchase_price;

- GROUP BY Writing position
GROUP BY There are strict requirements for the writing order of clauses , Failure to comply with the requirements will result in SQL Unable to execute normally , The order of clauses that have appeared at present is :
1 SELECT → 2. FROM → 3. WHERE → 4. GROUP BY
The first three items are used to filter the data ,GROUP BY Process the filtered data
-- stay WHERE Used in clauses GROUP BY
SELECT purchase_price, COUNT(*) FROM product
WHERE product_type = ' clothes '
GROUP BY purchase_price;
4.2、 Common errors in grouping query
When using aggregate functions and GROUP BY When clause , Common mistakes are :
- At the end of the aggregate function SELECT Clause specifies the use of columns other than aggregate keys COUNT Wait for the aggregate function ,SELECT If the column name appears in the clause , Can only be GROUP BY The column name specified in clause ( That's the aggregate bond ).
select count(product_type),product_name from productions;
/*[planner:8123]In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'product_name'; this is incompatible with sql_mode=only_full_group_by */
TiDB> select count(product_type),product_name from productions
-> group by product_name;
+---------------------+--------------+
| count(product_type) | product_name |
+---------------------+--------------+
| 1 | Punch |
| 1 | kitchen knife |
| 1 | Ball pen |
| 1 | motion T T-shirt |
| 1 | pressure cooker |
| 1 | Fork |
| 1 | T shirt |
| 1 | Clean the board |
+---------------------+--------------+
- stay GROUP BY Use column aliases in clause SELECT Clause can be passed through AS To specify an alias , But in GROUP BY Alias cannot be used in . Because in DBMS in ,SELECT Clause in GROUP BY Execute after clause .
- stay WHERE The reason for using aggregate function in is that the premise of using aggregate function is that the result set has been determined , and WHERE Still in the process of determining the result set , So contradictions can lead to errors . If you want to specify conditions , Out of commission WHERE, Can be in SELECT,HAVING( I'll talk about ) as well as ORDER BY The aggregate function is used in clause .
4.3、 Aggregate results specify conditions
Use table GROUP BY After grouping , Take out some of these groups : Can be in GROUP BY After use HAVING Clause ,HAVING The usage of is similar to WHERE.
HAVING Clause is used to filter groups , have access to Numbers 、 Aggregate functions and GROUP BY The column name specified in ( Polymerization bond ).
HAVING Clause is equivalent to WHERE.
-- Numbers
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type
HAVING COUNT(*) = 2;
-- HAVING product_type = " clothes "
5、 Sorting of query results
5.1、ORDER BY sentence
SQL The execution results in are arranged randomly , When you need to sort in a specific order , have access to ORDER BY Clause .
SQL In the use of HAVING When clause SELECT The order of statements is :
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.
-- grammar
SELECT < Name 1>, < Name 2>, < Name 3>, ……
FROM < Table name >
ORDER BY < Sort base column 1>, < Sort base column 2>, ……
The default is ascending , The descending order is DESC
-- Descending order
SELECT product_id, product_name, sale_price, purchase_price
FROM product
ORDER BY sale_price DESC;
5.2、 Multiple queries
- Multiple sorting , It is mainly based on the first sorting key , The second is auxiliary .
SELECT product_id, product_name, sale_price, purchase_price
FROM product
ORDER BY sale_price, product_id;

5.3、 contain NULL Inquire about
1. When the column name used for sorting contains NULL when ,NULL It will be summarized at the beginning or end .
SELECT product_id, product_name, sale_price, purchase_price
FROM product
ORDER BY purchase_price;

stay MySQL in ,NULL The value is considered to be better than any Not NULL Low value , therefore , When the order is ASC( Ascending ) when ,NULL The value appears first , And when the order is DESC( Descending ) when , Sort at the end .
If you want to specify that there is NULL The line appears on the first or last line , Require special treatment .
1. take NULL Value at the end of the line , At the same time, all Not NULL Values are arranged in ascending order .
For number or date types , You can add a negative sign before the sort field (minus) To get the reverse sort .(-1、-2、-3…-∞)
select purchase_price from productions
order by -purchase_price desc;

For character type or character type number , This method may not get the expected sorting results , have access to IS NULL Comparison operator . in addition ISNULL( ) Function is equivalent to using IS NULL Comparison operator .
String comparison is the definition of the last line .(null or not null)
select purchase_name from productions
order by purchase_name is null, name asc;
2. take NULL The value comes first , At the same time, all Not NULL Values are arranged in reverse order .
For number or date types , You can add a negative sign before the sort field (minus) To achieve .(-∞…-3、-2、-1).
select purchase_price from productions
order by -purchase_price;

For character type or character type number , This method may not get the expected sorting results , have access to IS NOT NULL Comparison operator . in addition !ISNULL( ) Function is equivalent to using IS NOT NULL Comparison operator .
select purchase_name from productions
order by purchase_name is not null, name desc;
6、 Exercises
database information :
CREATE DATABASE shop
CREATE TABLE productions
(product_id CHAR(4) NOT NULL,
product_name VARCHAR(100) NOT NULL,
product_type VARCHAR(32) NOT NULL,
sale_price INTEGER ,
purchase_price INTEGER ,
regist_date DATE ,
PRIMARY KEY (product_id));
INSERT INTO productions VALUES('0001', 'T shirt ', ' clothes ', 1000, 500, '2009-09-20');
INSERT INTO productions VALUES('0002', ' Punch ', ' Office Supplies ', 500, 320, '2009-09-11');
INSERT INTO productions VALUES('0003', ' motion T T-shirt ', ' clothes ', 4000, 2800, NULL);
INSERT INTO productions VALUES('0004', ' kitchen knife ', ' Kitchenware ', 3000, 2800, '2009-09-20');
INSERT INTO productions VALUES('0005', ' pressure cooker ', ' Kitchenware ', 6800, 5000, '2009-01-15');
INSERT INTO productions VALUES('0006', ' Fork ', ' Kitchenware ', 500, NULL, '2009-09-20');
INSERT INTO productions VALUES('0007', ' Clean the board ', ' Kitchenware ', 880, 790, '2008-04-28');
INSERT INTO productions VALUES('0008', ' Ball pen ', ' Office Supplies ', 100, NULL, '2009-11-11');
as follows :
6.1
Write a SQL sentence , from product( goods ) Select from the table “ Registration date (regist_date) stay 2009 year 4 month 28 After the day ” The goods , Query results should contain product name and regist_date Two .
select product_name, regist_date
from productions
where regist_date > '2009-4-28';

6.2
Please say yes to product The table is executed as follows 3 strip SELECT The return result of statement .
null Operators cannot be used to judge , Only use IS NULL / IS NOT NULL
So the result is empty
①
SELECT *
FROM product
WHERE purchase_price = NULL;
②
SELECT *
FROM product
WHERE purchase_price <> NULL;
③
SELECT *
FROM productions
WHERE product_name > NULL;
6.3
SELECT Statements can be made from product Take out from the table “ Unit sales price (sale_price) Compared with the purchase price (purchase_price) Higher than 500 Above JPY ” The goods . Please write two items that can get the same result SELECT sentence . The results are shown below :
product_name | sale_price | purchase_price
-------------+------------+------------
T shirt | 1000 | 500
motion T T-shirt | 4000 | 2800
pressure cooker | 6800 | 5000
-- sentence 1
select product_name, sale_price, purchase_price
from productions
where sale_price >= purchase_price+500;
-- sentence 2
select product_name, sale_price, purchase_price
from productions
where sale_price-500 >= purchase_price;

6.4
Please write a SELECT sentence , from product Select from the table to meet “ After 10% discount on unit sales price, the profit is higher than 100 Japanese yen office supplies and kitchen utensils ” Record of conditions . The query results should include product_name Column 、product_type And the profit after 10% discount on the sales unit price ( The alias is set to profit).
Tips : 10% off the unit price , Can pass sale_price Multiply the value of the column by 0.9 get , The profit can be subtracted from this value purchase_price The value of the column gets .
select product_name, product_type, (sale_price*0.9-purchase_price) as profit
from productions
where (product_type = ' Office Supplies ' or product_type = ' Kitchenware ') and
(sale_price*0.9-purchase_price >100);

6.5
Please point out the following SELECT All the grammatical errors in the statement .
-- Ben SELECT There is an error in the statement .
SELECT product_id, SUM(product_name)
FROM product
GROUP BY product_type
WHERE regist_date > '2009-09-01';
error :
- Character field product_name It can't be SUM polymerization
- WHERE The sentence should be written in GROUP BY The statement before ( FROM After statement )
- GROUP BY Field (product_type) And SELECT The fields are different (product_id)
6.6
Please write one SELECT sentence , Find out the sales unit price ( sale_price Column ) The total value is greater than the purchase unit price ( purchase_price Column ) Total value 1.5 Times the commodity category . The results are shown below .
product_type | sum | sum
-------------+------+------
clothes | 5000 | 3300
Office Supplies | 600 | 320

select product_type, sum(sale_price) as sum , sum(purchase_price) as sum
from productions
GROUP BY product_type
having sum(sale_price) > sum(purchase_price)*1.5;

6.7
We used it before SELECT The sentence is selected product( goods ) All the records in the table . We used ORDER BY Clause to specify the sort order , But now I can't remember how it was designated . Please refer to the following execution results , reflection ORDER BY The content of the clause .
select * from product
order by -regist_date, purchase_price;

-- How to write it 2
SELECT *
FROM product
ORDER BY !ISNULL(regist_date) , regist_date DESC, sale_price;
-- How to write it 3
SELECT *
FROM product
ORDER BY COALESCE(regist_date, 'ZZZZ') DESC , sale_price;
边栏推荐
- 7. F1方程式冠军
- 基于Flink实时项目:用户行为分析(一:实时热门商品统计)
- New experience of mlvb cloud live broadcast: millisecond low latency live broadcast solution (with live broadcast performance comparison)
- In depth learning report (2)
- ADB shell screen capture command
- Flink中的状态管理
- Deep understanding of golang - closures
- The difference between golang slice make and new
- Solve the problem that CUDA cannot accelerate GPU in pytoch
- One of the Flink requirements - processfunction (requirement: alarm if the temperature rises continuously within 30 seconds)
猜你喜欢

Solve the problem that CUDA cannot accelerate GPU in pytoch

PlantCV中文文档

进入2022年,移动互联网的小程序和短视频直播赛道还有机会吗?

不止直播:腾讯云直播MLVB 插件除了推流/拉流还有哪些亮眼功能

李宏毅机器学习(2017版)_P14:反向传播

Naive Bayes Multiclass训练模型

Flink based real-time project: user behavior analysis (I: real-time popular product statistics)

Flink sliding window understanding & introduction to specific business scenarios

IDEA导入外部项目时pom文件的依赖无效问题解决

The difference between golang slice make and new
随机推荐
下一代互联网:视联网
Uni-app 小程序 App 的广告变现之路:Banner 信息流广告
More than live streaming: what other eye-catching functions does Tencent cloud live mlvb plug-in have besides streaming / streaming
One of the Flink requirements - sideoutput (Application of side output flow: output the temperature higher than 30 ℃ to the mainstream, and output the temperature lower than 30 ℃ to the side flow)
Solve the problem of direct blue screen restart when VMware Workstation virtual machine starts
最长公共子串
网站日志采集和分析流程
Li Hongyi machine learning (2017 Edition)_ P6-8: gradient descent
Verilog的基本语法
Redisson working principle - source code analysis
堆排序相关知识总结
解决Pytorch中Cuda无法GPU加速问题
Neo4j Basic Guide (installation, node and relationship data import, data query)
Li Hongyi machine learning (2017 Edition)_ P14: back propagation
Android——数据持久化技术(三) 数据库存储
The difference between golang slice make and new
Li Hongyi machine learning (2017 Edition)_ P13: deep learning
Flink1.11 write MySQL test cases in jdcb mode
6. 世界杯来了
VSCode2015下编译darknet生成darknet.ext时error MSB3721:XXX已退出,返回代码为 1。