当前位置:网站首页>SQL things
SQL things
2022-07-25 18:16:00 【Not reassuring】
Preface
This blog is Datawhale The first 39 period 《SQL programing language 》 Punch in study notes .
Open source tutorial address :https://github.com/datawhalechina/wonderful-sql.
task01: Get to know the database
1.1 Write a CREATE TABLE sentence , Used to create a Addressbook ( Address book ) surface , And for regist_no ( Registration number ) Column set primary key constraint

CREATE TABLE Addressbook
(regist_no INTEGER NOT NULL,
name VARCHAR(128) NOT NULL,
address VARCHAR(256) NOT NULL,
tel_no CHAR(10) ,
mail_address CHAR(20) ,
PRIMARY KEY (regist_no));
Knowledge point :
Build table (CREATE TABLE) grammar :
CREATE TABLE < Table name >
( < Name 1> < data type > < Constraints required for this column > ,
< Name 2> < data type > < Constraints required for this column > ,
< Name 3> < data type > < Constraints required for this column > ,
< Name 4> < data type > < Constraints required for this column > ,
.
.
.
< Constraints for this table 1> , < Constraints for this table 2> ,……);
1.2 towards Addressbook Add postal_code Column
ALTER TABLE Addressbook ADD COLUMN postal_code CHAR(8) NOT NULL;
Knowledge point :
Add columns to the table (ALTER TABLE) The grammar of :
ALTER TABLE < Table name > ADD COLUMN < Definition of columns >;
1.2 towards Addressbook Add postal_code Column
ALTER TABLE Addressbook ADD COLUMN postal_code CHAR(8) NOT NULL;
Knowledge point :
Add columns to the table (ALTER TABLE + ADD COLUMN) The grammar of :
ALTER TABLE < Table name > ADD COLUMN < Definition of columns >;
Delete column from table ( ALTER TABLE + DROP COLUMN) The grammar of :
ALTER TABLE < Table name > DROP COLUMN < Name >;
1.3 Delete Addressbook surface
DROP table Addressbook;
Knowledge point :
Delete table syntax :
DROP TABLE < Table name > ;
1.4 Whether it is possible to write SQL Statement to restore deleted Addressbook surface
answer : Can not be , So backup is very important .
task02: Basic query and sort
Table used product :
2.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 product
WHERE regist_date>'2009-04-28';
Knowledge point :
Look up table grammar ( The most basic knowledge ):
SELECT < Name >, ……
FROM < Table name >
WHERE < Conditional expression >;
2.2 as follows 3 strip SELECT The return result of statement
①
SELECT * FROM product
WHERE purchase_price = NULL;

②
SELECT * FROM product
WHERE purchase_price <> NULL;

③
SELECT * FROM product
WHERE purchase_price > NULL;

Knowledge point :
(1) SELECT If followed by an asterisk (*) Represents the selection of all columns ;
(2) SQL The statement supports four operations and comparison operations ,<> representative “ and ~ It's not equal ”, Be similar to NOT.
2.3 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 :
-- The first one is :
SELECT product_name,sale_price,purchase_price
FROM product
WHERE sale_price-purchase_price >= 500;
-- The second kind :
SELECT product_name,sale_price,purchase_price
FROM product
WHERE sale_price >= purchase_price + 500;
2.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).
SELECT product_name,product_type, sale_price*0.9-purchase_price as profit
FROM product
WHERE sale_price*0.9-purchase_price >= 100
AND (product_type = ' Office Supplies ' OR product_type = ' Kitchenware ' );
Knowledge point :
AND Operator takes precedence over OR Operator , Want to give priority to OR operation , Need to use Brackets .
2.5 Please point out the following SELECT All the grammatical errors 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 .
error ②:WHERE The sentence should be written in GROUP BY The statement before ( FROM After statement ), Or use HAVING.
error ③:GROUP BY Field (product_type) And SELECT The fields are different (product_id).
Knowledge point :
(1) MAX / MIN The function is applicable to columns of text type and number type , and SUM / AVG The function is only applicable to columns of numeric type ;
(2) SQL The order in which statements are executed :FROM → WHERE → GROUP BY → SELECT → HAVING → ORDER BY;
(3) 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 ).
2.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 .
SELECT product_type , SUM(sale_price) , SUM(purchase_price)
FROM product
GROUP BY product_type
HAVING SUM(sale_price) > 1.5*SUM(purchase_price);

Knowledge point :
(1)HAVING Clause is used to filter groups , Constants can be used 、 Aggregate functions and GROUP BY The column name specified in ( Polymerization bond ).
(2)HAVING Clause must be consistent with GROUP BY Clause in conjunction with , And the limit is the grouping aggregation result .
2.7 Please write one SELECT sentence , Output the table shown below .

The observation data shows that , This form is based on regist_date Sort ( Descending ), To the same regist_date Medium purchase_price Sort ( Ascending ).
SELECT * FROM product
ORDER BY - regist_date ASC,purchase_price ASC;
Knowledge point :
(1)ASC: Ascending ;DESC: Descending .
(2) stay MySQL in ,NULL The value is considered to be better than any Not NULL Low value , So I want to put it on the first line in descending order , Special treatment required , Here is to add a minus sign before the sorting field (minus) To get the reverse sort (NULL The position is not affected ).
(3) because SQL The order in which statements are executed (2.5(2)),ORDER BY Statement can be used SELECT Clause .
(4) Of all keywords at this stage Writing order :SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY.
task03: Complex one ( Billion ) Query of points
This section is more important , It is recommended to go through the official documents .
3.1 Use product( goods ) Table as a reference table , Create a view that meets the following three conditions ( The view name is ViewPractice5_1).
- 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 .
CREATE VIEW ViewPractice5_1 (product_name, sale_price,regist_date)
AS
(SELECT product_name, sale_price,regist_date
FROM product
WHERE sale_price>=1000 AND regist_date='2009-09-20');
3.2 View created in exercise 1 ViewPractice5_1 Insert the following data , What kind of results will we get ?
INSERT INTO ViewPractice5_1 VALUES (' knife ', 300, '2009-11-02');
Report errors :Field of view ‘shop.viewpractice5_1’ underlying table doesn’t have a default value.
Cause analysis : Views are ultimately windows derived from tables , When inserting data into a view , At the same time, it will also report to the original table (product) Insert data insert data , However, multiple fields in the original table cannot be empty , So you can't insert .
3.3 Please write according to the following results SELECT sentence , among sale_price_avg List the average selling unit price of all goods .

SELECT product_id,product_name,product_type,sale_price,
(SELECT AVG(sale_price) FROM product) AS sale_price_avg
FROM product;
The first time , Instinctively AVG(sale_price) Together with other columns , But it will be reported when implementing “In aggregated query without GROUP BY…” Error of , The Internet actually offers a solution : Modify the sql_mode. But this kind of writing is really not standard , Here is a quick query , Combine the two results to solve .
3.4 Please write one according to the conditions in exercise 1 SQL sentence , Create a view with the following data ( The name is AvgPriceByType)

Along 3.3 Ideas written down :
CREATE VIEW AvgPriceByType (product_id, product_name, product_type, sale_price, sale_price_avg_type)
AS
(
SELECT product_id, product_name, product_type, sale_price,
(SELECT AVG(sale_price)
FROM product p2
WHERE p1.product_type = p2.product_type
GROUP BY p1.product_type) AS sale_price_avg_type
FROM product p1
);
Connect yourself to yourself , And then we can move on GROUP operation , I really can't think of it myself , Kneel down .
3.5 The four operations contain NULL when ( Without special treatment ), Whether the result of the operation must become NULL ?
Yes .
3.6 As used in this chapter product( goods ) The table is executed as follows 2 strip SELECT sentence , What kind of results can we get ?
①
SELECT product_name, purchase_price
FROM product
WHERE purchase_price NOT IN (500, 2800, 5000);

②
SELECT product_name, purchase_price
FROM product
WHERE purchase_price NOT IN (500, 2800, 5000, NULL);

Knowledge point :
(1) Predicates cannot be associated with NULL Compare
(2) NOT IN The parameter of cannot contain NULL, otherwise , The query result is usually empty .
3.7 According to the sales unit price ( sale_price ) Yes 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 :
SELECT
SUM(CASE WHEN sale_price <= 1000 THEN 1 ELSE 0 END) AS low_price,
SUM(CASE WHEN sale_price BETWEEN 1001 AND 3000 THEN 1 ELSE 0 END) AS mid_price,
SUM(CASE WHEN sale_price >= 3001 THEN 1 ELSE 0 END) AS high_price
FROM product;

Knowledge point : CASE expression
CASE WHEN < Evaluation expression > THEN < expression >
WHEN < Evaluation expression > THEN < expression >
.
.
ELSE < expression >
END
边栏推荐
- 使用sqldeveloper连接mysql
- Chapter 5 Basic Scripting: Shell Variables
- Why is the index in [mysql] database implemented by b+ tree? Is hash table / red black tree /b tree feasible?
- 实时云渲染有哪些优势
- Tang's little helper
- Introduction to cloud XR and development opportunities of cloud XR in 5g Era
- nodejs 简单例子程序之express
- Related operations of binary tree
- 1---电子实物认知
- Imx6 rtl8189ftv migration
猜你喜欢

Connect to MySQL using sqldeveloper

喜讯!瑞云科技被授予“海上扬帆”5G融合应用专委会成员单位

大话DevOps监控,团队如何选择监控工具?

Why the future of digitalization depends on 3D real-time rendering

ORB_SLAM3复现——上篇

Li Kai: the interesting and cutting-edge audio and video industry has always attracted me

CVE-2022-33891 Apache spark shell 命令注入漏洞复现

How to choose digital twin visualization platform

imx6 RTL8189FTV移植

Boomi won the "best CEO in diversity" and the "best company in career growth" and ranked among the top 50 in the large company category
随机推荐
乐观锁解析
C语言 libcurl交叉编译
List conversion problem
Wu Enda's machine learning programming operation cannot be suspended pause problem solved
Kendryte K210 在freertos上的lcd屏幕的使用
Thales launches solutions to help SAP customers control cloud data
C language libcurl cross compilation
Tensor to img && imge to tensor (pytorch的tensor转换)
C语言 整数与字符串的相互转换
喜讯!瑞云科技被授予“海上扬帆”5G融合应用专委会成员单位
Combined with GHS multi, use Reza E1 simulator to realize the simulation and debugging of Reza rh850 single chip microcomputer
网易严选库存中心设计实践
Related operations of figure
Sequential storage structure, chain storage structure and implementation of stack
二叉树的相关操作
LeetCode 101. 对称二叉树 && 100. 相同的树 && 572. 另一棵树的子树
MySQL optimistic lock
如何选择数字孪生可视化平台
Auditing相关注解
BiSeNet v1