当前位置:网站首页>100 important knowledge points that SQL must master: retrieving data
100 important knowledge points that SQL must master: retrieving data
2022-06-28 11:06:00 【Game programming】
2.1 SELECT sentence
SQL Sentences are made up of simple English words . These words are called
keyword , Every SQL Statements are made up of one or more keywords . The most frequently used
SQL The sentence is probably SELECT Statement . Its purpose is to retrieve from one or more tables
Information .
keyword (keyword)
As SQL Reserved words for components . Keywords cannot be used as table or column names . appendix D
Lists some frequently used reserved words .
In order to use SELECT Key table data , There must be at least two messages —— What do you want to choose ,
And where to choose .
explain : Understand examples
Examples in each course of this book SQL sentence ( And sample output ) Appendix is used A Described in the
A set of data files . If you want to understand and experiment with these examples ( I strongly recommend this ),
Please refer to the appendix A, It explains how to download or create these data files .Tips : Use the right database
utilize DBMS Can handle multiple databases ( See also 1 The analogy of file cabinet in class ). root
According to Appendix A After installing the sample table , I suggest you put them into a new database . If this
What kind of words , Make sure you have selected the database before processing , It's like you're creating a sample table
What I did before . In the learning process of the following lessons , If you encounter an unknown table error ,
It's probably not in the right database .
2.2 Retrieve a single column
We will start with a simple SQL SELECT The sentence starts with , This statement is as follows :
Input ▼
SELECT prod_nameFROM Products;
analysis ▼
The above statement makes use of SELECT Statements from Products Search for a table named prod_name
The column of . The required column names are written in SELECT After keyword , FROM Keyword indicates from which table
Search data in . The output of this statement is as follows :
Output ▼
prod_name-------------------Fish bean bag toyBird bean bag toyRabbit bean bag toy8 inch teddy bear12 inch teddy bear18 inch teddy bearRaggedy AnnKing dollQueen doll
Depending on what you use DBMS And the client , Maybe you will see a message indicating that you have retrieved
How many rows? , And how long it took . for example ,MySQL The command line will display something like this
One line of information :
9 rows in set (0.01 sec)
explain : Unordered data
If you try this query yourself , You may find that the order in which the output data is displayed is the same as
Different . It's normal for this to happen . If you don't explicitly sort the query results ( The next lesson is about
How to specify the order ), The returned data has no specific order . The order in which the data is returned can be
Can be the order in which data is added to the table , Maybe not . Just return the same number of rows ,
Just normal .
The simple one above SELECT Statement will return all rows in the table . The data is not filtered ( too
Filtering will result in a subset of the result set ), No sorting . These will be discussed in the next few lessons .
Tips : end SQL sentence
multiple SQL Statement must be semicolon ( ; ) Separate . Most of the DBMS You don't need to be in a single SQL
Add a semicolon after the statement , But there are also DBMS It may have to be in a single SQL Add a semicolon after the statement .
Of course , Always add a semicolon if you like . in fact , Even if you don't have to , add
Semicolons are certainly not bad .Tips :SQL Statement and case
Please note that ,SQL Statement is case insensitive , therefore SELECT And select It's the same .
Again , It's written in Select It doesn't matter . many SQL Developers like to SQL The key
Words are capitalized , Use lowercase for column names and table names , This makes the code easier to read and tune
try . however , It's important to realize that although SQL It's case insensitive , But the table name 、 Column
The name and value may be different ( It depends on the specific DBMS And how to configure ).Tips : Use spaces
Processing SQL When the sentence is , All spaces are ignored .SQL Statements can be written as long
A line , It can also be written on multiple lines . The following 3 The functions of the two writing methods are the same .
SELECT prod_name
FROM Products;
SELECT prod_name FROM Products;
SELECT
prod_name
FROM
Products;
Most of the SQL Developers think , take SQL The statement is divided into multiple lines, which is easier to read and debug
2.3 Retrieve multiple columns
To retrieve multiple columns from a table , Still use the same SELECT sentence . The only difference
Both must be in SELECT Multiple column names are given after the keyword , Column names must be separated by commas .
Tips : Beware of commas
When selecting multiple columns , Be sure to put a comma between the column names , But not after the last column name
Add . If you add a comma after the last column name , There will be mistakes .
Below SELECT Statements from Products Select from the table 3 Column .
Input ▼
SELECT prod_id, prod_name, prod_priceFROM Products;
analysis ▼
As in the previous example , This statement uses SELECT Statement from table Products Select data . In this case , It specifies 3 Column names , Separate column names with commas . Of this statement
Output is as follows :
Output ▼
prod_id prod_name prod_price--------- -------------------- ----------BNBG01 Fish bean bag toy 3.49BNBG02 Bird bean bag toy 3.49BNBG03 Rabbit bean bag toy 3.49BR01 8 inch teddy bear 5.99BR02 12 inch teddy bear 8.99BR03 18 inch teddy bear 11.99RGAN01 Raggedy Ann 4.99RYL01 King doll 9.49RYL02 Queen dool 9.49
explain : The data shows
SQL Statements generally return the original 、 Unformatted data , Different DBMS And the client
The way the data is displayed is slightly different ( If the alignment format is different 、 Different decimal places ). Lattice of data
Formalization is the expression of a problem , Not a retrieval problem . therefore , How to represent will generally be displayed in the
The application of data specifies . Usually, the actual retrieved data is rarely used directly ( No,
The format provided by the application ).
2.4 Retrieve all columns
In addition to specifying the required columns ( As mentioned above , One or more columns ), SELECT Statements can also check
Search all the columns without having to list them one by one . Use an asterisk in the position of the actual column name ( * ) Pass through
Fu can do this , As shown below .
Input ▼
SELECT *FROM Products;
analysis ▼
If given a wildcard ( * ), Then all columns in the table . The order of the columns is generally listed in the table
Present physical order , But not always . however ,SQL Data is rarely displayed directly ( Usually ,
Data is returned to the application , Format as needed , Then show it ). therefore , see
What problems should be caused .
Be careful : Use wildcards
generally speaking , Unless you really need every column in the table , Otherwise, it's better not to use * wildcard .
Although using wildcards can save you trouble , Don't explicitly list the required columns , But retrieval does not require
The columns to be retrieved usually slow down retrieval and application performance .Tips : Retrieve unknown Columns
Using wildcards has one big advantage . Because the column name is not specified explicitly ( Because the asterisk retrieves every
Column ), So you can retrieve columns with unknown names
2.5 Retrieve different values
As mentioned earlier , SELECT Statement returns all matching rows . however , If you don't want every value
Every time , What to do ? for example , You want to search Products All products in the table are for
Business oriented ID:
Input ▼
SELECT vend_idFROM Products;
Output ▼
vend_id----------BRS01BRS01BRS01DLL01DLL01DLL01DLL01FNG01FNG01
SELECT Statement returns 9 That's ok ( Even if there are only 3 A product supplier ), because Products
Table has 9 Products . So how to retrieve different values ?
The way is to use DISTINCT keyword , seeing the name of a thing one thinks of its function , It instructs the database to return only different
Value .
Input ▼
SELECT DISTINCT vend_idFROM Products;
analysis ▼
SELECT DISTINCT vend_id tell DBMS Just return to different ( Have uniqueness ) Of
vend_id That's ok , So as the output below , Only 3 That's ok . If you use DISTINCT Turn off
Key word , It must be placed directly in front of the column name .
Output ▼
vend_id
BRS01
DLL01
FNG01
Be careful : Can't use part of DISTINCT
DISTINCT Keywords apply to all columns , Not just the next column . example
Such as , You specify SELECT DISTINCT vend_id, prod_price , be 9 In the line
6 The rows will be retrieved , Because the specified two columns combine to have 6 Different results .
If you want to see what the difference is , You can try these two sentences :
SELECT DISTINCT vend_id, prod_price FROM Products;
SELECT vend_id, prod_price FROM Products;
2.6 Restriction result
SELECT Statement returns all matching rows in the specified table , Probably every line . If you just want to
Returns the first row or a certain number of rows , What to do ? This is feasible , Unfortunately
yes , This in various databases SQL The implementation is not the same .
stay SQL Server Use in SELECT when , It can be used TOP Keyword to limit the maximum number of returns
Shao Xing , As shown below :
Input ▼
SELECT TOP 5 prod_nameFROM Products;
Output ▼
prod_name-----------------8 inch teddy bear12 inch teddy bear18 inch teddy bearFish bean bag toyBird bean bag toy
analysis ▼
The above code USES SELECT TOP 5 sentence , Retrieve only the previous 5 Row data .
If you're using DB2, You have to use the following DB2 Peculiar SQL sentence :
Input ▼
SELECT prod_nameFROM ProductsFETCH FIRST 5 ROWS ONLY;
analysis ▼
FETCH FIRST 5 ROWS ONLY I will do it literally ( Take only before 5 That's ok ).
If you use Oracle, Need to be based on ROWNUM ( Row counter ) To calculate the line , like this :
Input ▼
SELECT prod_nameFROM ProductsWHERE ROWNUM <=5;
If you use MySQL、MariaDB、PostgreSQL perhaps SQLite, Need to use LIMIT
Clause , like this :
Input ▼
SELECT prod_nameFROM ProductsLIMIT 5;
analysis ▼
The above code uses SELECT Statement to retrieve a single column of data . LIMIT 5 instructions MySQL etc. DBMS Returns no more than 5 Row data . See the following code for the output of this statement .
In order to get the back 5 Row data , You need to specify where to start and the number of rows to retrieve , image
such :
Input ▼
SELECT prod_nameFROM ProductsLIMIT 5 OFFSET 5;
analysis ▼
LIMIT 5 OFFSET 5 instructions MySQL etc. DBMS Go back from 5 It works 5 Row data .
The first number is the number of rows retrieved , The second number refers to where to start . The output of this statement
What's the matter :
Output ▼
prod_name-------------------Rabbit bean bag toyRaggedy AnnKing dollQueen doll
therefore , LIMIT Specify the number of rows returned . LIMIT Band OFFSET Specify where to start .
In our case , Products Only in the table 9 Products , therefore LIMIT 5 OFFSET
5 Only returned 4 Row data ( Because there is no 5 That's ok ).
Be careful : The first 0 That's ok
The first row to be retrieved is 0 That's ok , Not the first. 1 That's ok . therefore , LIMIT 1 OFFSET
1 Will retrieve page 2 That's ok , Not the first. 1 That's ok .Tips :MySQL、MariaDB and SQLite shortcut
MySQL、MariaDB and SQLite You can put LIMIT 4 OFFSET 3 Statement reduced to LIMIT
3,4 . Use this syntax , The value before the comma corresponds to OFFSET , The value after the comma corresponds to
LIMIT ( Opposite , Be careful ).explain : Not all SQL The implementation is the same
I joined this section for only one reason , Just to explain ,SQL Although there is usually quite a
To achieve , But you can't take it for granted that it's always like this . Very basic statements tend to
It is interlinked. , But more complex statements are different . When you look for a problem SQL Explain
When making a resolution , Be sure to remember this .
2.7 Use notes
You can see ,SQL The statement is made by DBMS Instructions to process . If you want to include no processing
And executed text , What to do ? Why do you want to do this ? The reasons are as follows .
What we use here is SQL The sentences are very short , It's also very simple. . However , With SQL sentence
Lengthening , Complexity increases , You'll want to add some descriptive comments , This is convenient for you
For future reference , Or for the reference of subsequent participants of the project . These comments need to be embedded in SQL
Script , But it is obviously impossible to carry out practical DBMS Handle .( For relevant examples, please refer to appendix
record B Used in create.sql and populate.sql.)
This also applies to SQL At the beginning of the file , It may contain a description of the program and some
explain , Even the programmer's contact information .( Examples can also be found in the appendix B The one in
some .sql file .)
Another important application of annotations is to pause the execution of SQL Code . If you come across a long
SQL sentence , And just want to test part of it , Then you should comment out some code , In order to
DBMS Omit these notes .
quite a lot DBMS All support various forms of annotation Syntax . Let's first look at the in-line notes :
Input ▼
SELECT prod_name -- This is a comment FROM Products;
analysis ▼
Annotation use -- ( Two hyphens ) Embedded in the line . -- The following text is the comment , for example ,
This is used to describe CREATE TABLE The columns in the statement are very good .
Here is another form of inline comment ( But this form has some DBMS I won't support it ).
Input ▼
# This is a comment SELECT prod_nameFROM Products;
analysis ▼
Use... At the beginning of a line # , This whole line will be used as a comment . The script you provide in this book
create.sql and populate.sql You can see this form of annotation in .
You can also comment on multiple lines , Comments can stop and start anywhere in the script .
Input ▼
/* SELECT prod_name, vend_idFROM Products; */SELECT prod_nameFROM Products;
analysis ▼
Note from /* Start , To */ end , /* and */ Anything between is a comment . This way,
Often used to comment out code , As this example demonstrates , There are two definitions SELECT
sentence , But the first one won't execute , Because it has been commented out .
author : Guge academic
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
猜你喜欢
Katalon框架测试web(二十)自定义关键字以及上传弹窗操作
动态库(共享库)的制作和使用
Information hidden in the trend chart of Hong Kong London gold market
移动命令
Dataease installation upgrade
科研丨Web of Science检索技巧
Katalon当中的output使用方法
Katalon framework tests web (XX) custom keywords and upload pop-up operations
Docker modifies the user name and password of MySQL
How does ETF position affect spot gold price?
随机推荐
Ruoyi integrated building block report (NICE)
壓縮解壓
关于Pytorch中双向LSTM的输出表示问题
JSON模块、hashlib、base64
Spatial-Temporal时间序列预测建模方法汇总
Excel导入导出便捷工具类
Metersphere implements UI automation elements that are not clickable (partially occluded)
soapui的菜鸟教程
Mongo database
Threads and thread pools
MarkDown——基本使用语法
DlhSoft Kanban Library for WPF
How to distinguish and define DQL, DML, DDL and DCL in SQL
Metersphere实现UI自动化元素不可点击(部分遮挡)
JS基础1-JS引入与运算符
【实操】Appium Settings app is not running after 5000ms
Realization of a springboard machine
【Qt】connect 语法参考实现
[function suggestion] select a space when multiple workspaces are started
零基础自学SQL课程 | IF函数