当前位置:网站首页>Data query of server SQL. The most important chapter in database learning

Data query of server SQL. The most important chapter in database learning

2022-06-25 20:51:00 Master SongGe

First, let's talk about why data query is the most basic , Now learn java,Javaweb And other knowledge will involve connecting to the database , A common database connection is a connection mysql、server sql and oracle. Most of all mysql, Among them, connecting to the database is more used sql A statement is a query statement , I've basically covered everything below . So data query is very important . basal
Select column
example 1: From database sales Product list for Product The product is found in ID(ProductID)、 The product name (ProductName) And unit price (Price) Data information
namely :USE sales
GO
SELECT ProductID, ProductName, Price
FROM Product
Select all columns
example 2: Show Orders All information in the table
namely :SELECT*
FROM Orders
Change column headings
example 3: Display the salesperson's name , Gender , Date of birth and address information
namely :SELECT SaleName AS’ full name ’,Sex AS’ Gender ’,Birthday AS Date of birth ”,Address AS’ Address ’
FROM Seller
among AS It can be omitted
Select row
example 4: Inquire about Product The price in the table is lower than 5 Meta product information
namely :SELECT ProductID,ProductName,Price
FROM Product
WHERE Price<5.0
example 5: Ask the salesperson Seller In the male salesperson's information
namely :SELECT SaleID,SaleName,Address,Telephone
FROM Seller
WHERE Sex=’ male ’
example 6: Query order table Orders, The show is not c02, or c03 Information about orders placed by customers
namely :SELECT*
FROM Ordes
WHERE NOT(CustomerID=’c02’ OR CustomerID=’c03’)
Use string fuzzy matching
The meaning of the matcher
Match symbol describe
% : Any string containing zero or more characters
_ : Represents an arbitrary character
[] : Represents any single character in the specified range
[^] : Represents any single character that is no longer within the specified range
Application instance of the matching character
LIKE’RA%’ : Search for a letter RA All strings at the beginning
LIKE’%ion’ : Search with letters ion All strings at the end
LIKE’%ir%’ : Search for letters anywhere ir All strings of
LIKE’_mt’ : Search with letters mt All three letters at the end of the string
LIKE’[BC]%’ : Search with letters B or C All strings at the beginning
LIKE’[B-K]air’ : Search with letters B To K Start with any letter in , With air a null-terminated string
LIKE’B[^a]%’ : Search with letters B start , Not the second letter a All strings of
example 7: Query the salesperson table Seller All the sales personnel information of Zhang, Wang and Li in
namely :SELECT*FROM Seller WHERE SaleName LIKE’[ Zhang Wang Li ]%’
Use the query list
example 8: Inquire about Seller In the table SaleID by s01,s05,s07 Information about the salesperson
namely :SELECT SaleID,SaleName,Sex,Birthday,HireDate,Address
FROM Seller
WHERE SaleID=’S01’ OR SaleID=’S05’ OR SaleID=’S07’
Be careful : And IN The relative predicate is NOT IN, Used to query records whose field values do not belong to the specified set
Determination of null value
stay SQL in , use NULL Indicates null value , It's just a symbol , Not equal to space , Neither 0
Retrieve salesperson table Seller Employment date field in HireDate The data of the salesperson whose value is empty
namely :SELECT*FROM Seller WHERE HireDate IS NULL
Sort
Singleton sort
example 9: In descending order of the date of birth column Seller surface
namely :SELECT SaleID,SaleName,Sex,Birthday,Address
FROM Seller
ORDER BY Birthday DESC
Be careful : keyword ASC Expressing ascending order , Omission , keyword DESC Representation of descending order
You can also say
namely :
SELECT SaleID,SaleName,Sex,Birthday,Address
FROM Seller
ORDER BY 3
Field Birthday stay SELECT In a sentence, you are at the 3 The location of , once ORDER BY 3 Clause means to follow Birthday The field shows the salesperson in ascending order . Because it doesn't mean ASC and DESC, So the default ascending order .
Multi column sorting
example 10: Inquire about Orders Table data , According to the first CustomerId Ascending order , When CustomerID If it's the same, follow SaleID Descending order
namely :SELECT*
FROM Orders
ORDER BY CustomerID,SaleID DESC
TOP keyword
stay SELECT Use in clause TOP Keyword limits the number of rows returned to the result set
among TOP integer: Represents the first few rows in the returned result set , use integer Indicates the number of rows returned .
TOP integer PERCENT: The number of rows returned is expressed as a percentage
example 11: Respectively from the Customer Before... Retrieved from the table 5 Line and front 20% Customer information for
namely :SELECT TOP 5*
FROM Customer
SELECT TOP 20 PERCENT*
FROM Customer
example 12: Inquire about Product The highest price in the list 6 A commodity
namely :SELECT TOP 6*
FROM Product
ORDER BY Price DESC
DISTINCT keyword
among :ALL: Run the occurrence of duplicate data rows , Is the default keyword
example 13: Query the order details table OrderDetail, Displays the product number ordered , If multiple orders place the same product , The product number only needs to be displayed once
namely :SELECT ProductID
FROM OrderDetail
SELECT DISTINCT ProductID
FROM OrderDetail
Internal connection
An inner join is a comparison of the values of columns shared by multiple tables through join conditions .
example 14:
Show OrderID by “10249” Of ProductID,ProductName.Quantity And Price. because OrderID、ProductID as well as Quantity These three columns are from OrderDetail surface , and ProductName、Price From Product surface , Therefore, the query involves multi table query .
That is, method 1 , stay from Partially write multiple table names ,where Partial write connection condition
SELECT OrderID,OrderDetail,ProductID,ProductName,Price,Quantiy
FROM OrderDetail,Product
WHERE OrderID=’10249’ AND OrderDetail.ProductID=Product.ProductID
Method 2 , stay FROM In use JOIN ON Connect
SELECT OrderID,O.ProductID,ProductName,Price,Quantiy
FROM OrderDetail O INNER JOIN Product P ON O.ProductID=P.ProductID
WHERE OrderID=’10249’
example 15: Join query of three tables ,
namely :SELECT OrderID,O.CustomerID,ConnectName,O.SaleID,SaleName
FROM Orders O INNER JOIN Customer C ON O.CustomerID=C.CustomerID
INNER JOIN Seller S ON O.SaleID=S.SaleID
WHERE OrderID=’10248’
The left outer join
Outer join shows a result set that contains all rows in one table and matching rows in another table
Left outer link back LEFT OUTER JOIN The left side of the keyword specifies the table ( coordinate ) All rows and the right side of the specified table ( Right table ) Matching rows .
:16: Show... For all products ProductID,ProductName,Price, And those ordered by customers OrderID,Quantity
namely :SELECT P.ProductID,ProductName,Price,OrderID,Quantity
FROM Product P LEFT OUTER JOIN OrderDetail O
ON P.ProductID=O.ProductID
The result is that all rows in the left table are displayed regardless of whether the product is ordered in the right table
Right connection
Opposite to the left outer connection
The example is the same as above , Change the left outer connection to the right outer connection
namely :SELECT OrderID,Quantity,P.ProductID,ProductName,Price
FROM OrderDetail O RIGHT OUTER JOIN Product P
ON O.ProductID=P.ProductID
Complete external connection
Complete outer connection is a combination of left outer connection and right outer connection , This connection returns all matched and unmatched rows from both tables , Where matching records are displayed only once , In the case of non matching rows , Columns for which data is not available will display NULL value
example 17: towards Category Table add new category – clothing , Then the query
namely :INSERT INTO Category VALUES(4,’ clothing ’,NULL)
SELECT ProductID,ProductName,Price,Stocks,C.CategoryID,CategoryName
FROM Product P FULL OUTER JOIN Category C
ON P.CategoryID=C.CategoryID
Cross connect
Cross join between two tables , Each row in the left table is connected with each row in the right table . therefore , The number of rows in the result set is the number of rows in the left table multiplied by the number of rows in the right table , This product is also called a Cartesian product , keyword CROSS JOIN
namely :SELECT CustomerID,CompanyName,ConnectName,SaleID,SaleName
FROM Customer CROSS JOIN Seller
The query result set contains 81 Bar record , Relatively large , In fact, cross - linking has no practical significance , Usually used to test all possible situations
Aggregate functions
Functions specially used for numerical statistics .
example 18: seek Product Evaluation prices of all products in the table , Highest price , The lowest price , And total inventory
namely :SELECT AVG(Price) AS ‘ The average price ’ FROM Product
SELECT MAX(Price) AS ‘ The highest price ’ FROM Product
SELECT MIN(Price) AS ‘ The lowest price ’ FROM Product
SELECT SUM(Stocks) AS ‘ Total inventory ’ FROM Product
example 19: Statistics Customer The number of customers with mobile phones in the table
namely :SELECT COUNT(MobilePhone) AS Number of customers with mobile phones
FROM Customer
example 20: Statistics Product standard , Inventory >200 Of products
namely :SELECT COUNT(ProductID)
FROM Product
WHERE Stocks>200
Group summary words
Only a single summary result can be returned by using the aggregate function , If you need to display the summary data of the group , Must use GROUP BY Words and expressions , The function of this clause is to divide the data in the table into multiple groups according to the specified columns and then summarize them
example 21: take Product The data in the table is displayed by CategoryID Grouping , Then calculate the average price and total inventory of each group of products
namely :SELECT CategoryID,AVG(Price) AS ‘ The average price ’,SUM(Stocks) AS ‘ Total inventory ’
FROM Product
GROUP BY CategoryID
HAVING Words can further exclude groups that do not meet the conditions
example 22: Based on the previous example, only the average price is lower than 10 Meta group summary information
namely :SELECT CategoryID,AVG(Price) AS ‘ The average price ’,SUM(Stocks) AS ‘ Total inventory ’
FROM Product
GROUP BY CategoryID
HAVING AVG(Price)<10
Be careful , When it exists at the same time GROUP BY Words and expressions ,HAVING Words and sentences WHERE Word sentence time , The execution sequence is first WHERE After sentence GROUP BY Words and sentences again HAVING Words and expressions
example 23: List all prices above 5 Yuan and the average price of the group is higher than 15 The type of product of yuan 、 Average price and total inventory
namely :SELECT CategoryID,AVG(Price) AS ‘ The average price ’,SUM(Stocks) AS ‘ Total inventory ’
FROM Product
WHERE Price>5
GROUP BY CategoryID
HAVING AVG(Price)>15
First according to where The conditional filter price set by the unit is lower than 5 Yuan's products , This may change the results of the summary and affect HAVING Groups filtered out based on these in sentences
nested queries
The previous queries are all single-layer queries , A nested query is defined as a SELECT Another one is embedded in the query SELECT Inquire about . The outer SELECT Statements are called external queries , Inside SELECT Statement called subquery
When using subqueries, you should pay attention to :
Subqueries can be nested at multiple levels
Subquery requires parentheses () Cover up
Cannot use in subquery INTO Clause
In subquery SELECT You can't use image,text or ntext data type
The type of the return value of the subquery is single column single value
example 24: Inquire about OrderID by “10222” Customer information for , Inquire about OrderID by “10222” Specific steps for customer information
1. retrieval Orders surface , lookup OrderID by “10222” Of CustomerID
namely :SELECT CustomerID
FROM Orders
WHERE OrderID=’10222’
The execution result is “02”, That is, the order number is “10222” The order for is customer number “02” Of customers
2. Inquire about Customer surface , find CustomerID by “02” Customer details for
example 25: Inquire about Customer surface , find CustomerID by “02” Customer details for
namely :SELECT CustomerID,CompanyName,ConnectName,Address,ZipCode,Telephone
FROM Customer
WHERE CustomerID=’02’
3. You can change the first query into a subquery and combine two query statements , That is, nested query :
namely :SELECT CusomerID,CompanyName,ConnectName,Address,ZipCode,Telephone
FROM Customer
WHERE CustomerID=(
SELECT CustomerID
FROM Orders
WHERE OrderID=’10222’
)
The execution process of this nested query is : First evaluate the subquery ( Only once ), Find out OrderID by ’10222’,CustomerID by ’02’, Then make an external query , External queries depend on the results of subqueries
The return value type of the subquery is single column multi value
In the previous example , The result of the subquery is the single column single value data for comparison , If the subquery returns a single column with multiple values , You must use the keyword before the subquery ALL or ANY or IN
keyword meaning
ALL : Compare all values of the subquery
ANY: Compare any value of the subquery
IN : Belong to the relationship
NOT IN : Does not belong to or is not a member of a collection
example 25: Query order ID by “10248” Information about the products ordered
namely :SELECT*
FROM Product
WHERE ProductID=ANY(
SELECT ProductID
FROM OrderDetail
WHERE OrderID=’10248’
example 26: Modify the above example , Use keywords IN
SELECT*
FROM Product
WHERE ProductID IN(
SELECT ProductID
FROM OrderDetail
WHERE OrderID=’10248’
)
The query process is still divided into two steps , First, the internal sub query returns the order ID by “10248” Products ordered by ID(P01003,P01005,P02002). These values are then carried into the external query , stay Product Find the above... In ID Matching product information .
The query condition of the subquery depends on the external query
example 27: Show Customer The total number of orders per customer in the table
namely :SELECT CustomerID,CompanyName,Address,(
SELECT COUNT(*)
FROM Orders o
WHERE c.CustomerID=o.CustomerIN
GROUP BY CustomerID
)AS Order quantity
FROM Customer c
The process of solving a query in a correlation generally involves 4 A step
1) An external query obtains a row of records , Then pass the record to the internal query .
2) The internal query is executed according to the passed value
3) The internal query returns the result to the external query , External queries use these values to complete the processing process
4) repeat .. Until all the record lines in the external query are checked
With the keyword [NOT]EXISTS Subquery of
stay WHERE Used in clauses EXISTS keyword , Indicates whether the result set of the subquery is empty
example 28: Use keywords EXISTS Find the details of the customer who placed the order
namely :SELECT*
FROM Customer
WHERE EXISTS(
SELECT*
FROM Orders
WHERE Customer.CustomerID=Orders.CustomerID
)
Merged data set
example 29: use UNION The clause will Customer In the table CustomerID、ConnectName And Seller In the table SaleID、SaleName Combine in one result set
namely :SELECT CustomerID,ConnectName FROM Customer
UNION
SELECT SaleID,SaleName FROM Seller
Create a new table based on the query
The column of the new table is SELECT Clause , The data type and nullable attribute of the column in the original table remain unchanged , But all other information such as default 、 Constraints, etc. are ignored
example 30: Will example 10 Save the query results in to a new table temp_orders
namely :SELECT*
INTO temp_orders
FROM Orders
ORDER BY CustomerID,SaleID,DESC

原网站

版权声明
本文为[Master SongGe]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202181337352145.html