当前位置:网站首页>MySQL learning record (6)
MySQL learning record (6)
2022-07-02 21:29:00 【White_ Silence (Learning version)】
1. View
Definition : View is a virtual table , rely on select Sentence creation
Reason for creating view :
- 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.1 Syntax for creating views
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 .
View name In the database, it needs to be only Of , Cannot have the same name as other views and tables .
When defining a view Not to be used ORDER BY sentence
Create view :
Views based on a single table
CREATE VIEW productsum (product_type, cnt_product)
AS
SELECT product_type, COUNT(*)
FROM product
GROUP BY product_type ;
Views based on multiple tables
-- First create a new table
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);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000A', ' Tokyo ', '0002', 50);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000A', ' Tokyo ', '0003', 15);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0002', 30);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0003', 120);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0004', 20);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0006', 10);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000B', ' Nagoya ', '0007', 40);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0003', 20);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0004', 50);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0006', 90);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000C', ' Osaka ', '0007', 70);
INSERT INTO shop_product (shop_id, shop_name, product_id, quantity) VALUES ('000D', ' Fukuoka, ', '0001', 100);
-- stay productsum shop_product Create a view based on
CREATE VIEW view_shop_product(product_type, sale_price, shop_name)
AS
SELECT product_type, sale_price, shop_name
FROM product,
shop_product
WHERE product.product_id = shop_product.product_id;
1.2 Modify the syntax of the view structure
ALTER VIEW < View name > AS <SELECT sentence >
-- Modify the view
ALTER VIEW productSum
AS
SELECT product_type, sale_price
FROM Product
WHERE regist_date > '2009-09-11';
1.3 Update the view
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 .
That is, update and modify the view , It is essentially a modification of the basic table .
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 .
-- The statement that updates the view , Use UPDATE SET
UPDATE productsum
SET sale_price = '5000'
WHERE product_type = ' Office Supplies ';
1.4 Delete view
DROP VIEW < View name 1> [ , < View name 2> …]
DROP VIEW productsum;
2. Subquery
Subquery refers to a query that is nested within another query statement by one query statement , The subquery result is used as the outer layer of another query Filter conditions , Queries can be Based on one or more tables .
Subqueries are one-time , It will not be saved as a view .
2.1 nested subqueries
-- nested subqueries
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 subquery 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 .
-- For simplicity and efficiency , Try to minimize SELECT Iteration of subquery statements
2.2 Scalar subquery ( Single subquery )
Singleness is what is required SQL sentence
-- Query the goods whose sales unit price is higher than the average unit price
SELECT product_id, product_name, sale_price
FROM product
WHERE sale_price > (SELECT AVG(sale_price) FROM product);
Only one value can be returned , That is to return the specific... In the table A column of a row
SELECT product_id,
product_name,
sale_price,
(SELECT AVG(sale_price)
FROM product) AS avg_price
FROM product;
2.3 Associated subquery
The associated sub query connects the internal and external queries to filter data
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);
-- The internal table is P2, The external table is P1, Use WHERE Connect the two tables together
The execution process of association query :
- 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
Exercises 1
Create a view that meets the following three conditions ( The view name is ViewPractice5_1). 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 .
CREATE VIEW ViewPractice5_1
AS
(SELECT product_name,sale_price,regist_date
FROM product
WHERE sale_price >= 1000 AND regist_date="2009-09-20" );
View created in exercise 1 ViewPractice5_1 Insert the following data , What's the result ?
SQL Something went wrong , I don't know the result
-- Please write according to the following results SELECT sentence , among sale_price_all List the average selling unit price of all goods .
/*product_id | product_name | product_type | sale_price | sale_price_all
------------+-------------+--------------+------------+---------------------
0001 | T shirt | clothes | 1000 | 2097.5000000000000000
0002 | Punch | Office Supplies | 500 | 2097.5000000000000000
0003 | motion T T-shirt | clothes | 4000 | 2097.5000000000000000
0004 | kitchen knife | Kitchenware | 3000 | 2097.5000000000000000
0005 | pressure cooker | Kitchenware | 6800 | 2097.5000000000000000
0006 | Fork | Kitchenware | 500 | 2097.5000000000000000
0007 | Clean the board | Kitchenware | 880 | 2097.5000000000000000
0008 | Ball pen | Office Supplies | 100 | 2097.5000000000000000*/
SELECT product_id,product_name,product_type,sale_price,
(SELECT AVG(sale_price)
FROM product) AS sale_price_all
FROM product
ORDER BY product_id;
Please write one according to the conditions in exercise 1 SQL sentence , Create a view with the following data ( The name is AvgPriceByType).
product_id | product_name | product_type | sale_price | avg_sale_price
------------+-------------+--------------+------------+---------------------
0001 | T shirt | clothes | 1000 |2500.0000000000000000
0002 | Punch | Office Supplies | 500 | 300.0000000000000000
0003 | motion T T-shirt | clothes | 4000 |2500.0000000000000000
0004 | kitchen knife | Kitchenware | 3000 |2795.0000000000000000
0005 | pressure cooker | Kitchenware | 6800 |2795.0000000000000000
0006 | Fork | Kitchenware | 500 |2795.0000000000000000
0007 | Clean the board | Kitchenware | 880 |2795.0000000000000000
0008 | Ball pen | Office Supplies | 100 | 300.0000000000000000
/* Tips : The key is avg_sale_price Column . Different from exercise 3 , Here we need to calculate It is the average selling unit price of each commodity type . This is the same as using the associated subquery . in other words , This column can be created using the associated subquery . The question is where to use this associated subquery .*/
CREATE VIEW AvgPriceByType
AS (SELECT product_id,product_name,product_type,sale_price,
(SELECT avg(sale_price)
from product AS p2
WHERE p1.product_type=p2.product_type
GROUP BY p1.product_type) AS avg_sale_price
FROM product AS p1);
边栏推荐
- MySQL learning notes (Advanced)
- Analysis of enterprise financial statements [3]
- [fluent] dart technique (independent main function entry | nullable type determination | default value setting)
- Go language learning summary (5) -- Summary of go learning notes
- Redis -- three special data types
- Plastic granule Industry Research Report - market status analysis and development prospect forecast
- Send blessings on Lantern Festival | limited edition red envelope cover of audio and video is released!
- Construction and maintenance of business website [3]
- This team with billions of data access and open source dreams is waiting for you to join
- Construction and maintenance of business websites [9]
猜你喜欢
[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second
[question brushing diary] classic questions of dynamic planning
[dynamic planning] p1220: interval DP: turn off the street lights
[shutter] the shutter plug-in is used in the shutter project (shutter plug-in management platform | search shutter plug-in | install shutter plug-in | use shutter plug-in)
[shutter] statefulwidget component (pageview component)
One week dynamics of dragon lizard community | 2.07-2.13
Spend more time with your computer on this special holiday, HHH
[shutter] statefulwidget component (image component | textfield component)
Hot backup routing protocol (HSRP)
[hands on deep learning]02 softmax regression
随机推荐
China Indonesia advanced wound care market trend report, technological innovation and market forecast
Redis -- three special data types
[shutter] shutter layout component (Introduction to layout component | row component | column component | sizedbox component | clipoval component)
Longest public prefix of leetcode
Get weekday / day of week for datetime column of dataframe - get weekday / day of week for datetime column of dataframe
AES encryption CBC mode pkcs7padding filling Base64 encoding key 32byte iv16byte
When Valentine's Day falls on Monday
[fluent] dart function (function composition | private function | anonymous function | function summary)
[shutter] the shutter plug-in is used in the shutter project (shutter plug-in management platform | search shutter plug-in | install shutter plug-in | use shutter plug-in)
Share the easy-to-use fastadmin open source system - Installation
Golang embeds variables in strings
Research Report on the overall scale, major manufacturers, major regions, products and applications of friction dampers in the global market in 2022
I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
2021 v+ Quanzhen internet global innovation and Entrepreneurship Challenge, one of the top ten audio and video scene innovation and application pioneers
Go web programming practice (1) -- basic syntax of go language
Accounting regulations and professional ethics [19]
Web3js method to obtain account information and balance
Add two numbers of leetcode
Research Report on plastic antioxidant industry - market status analysis and development prospect forecast
Research Report on the overall scale, major manufacturers, major regions, products and applications of swivel chair gas springs in the global market in 2022