当前位置:网站首页>Advanced SQL statement 1 of Linux MySQL database
Advanced SQL statement 1 of Linux MySQL database
2022-06-25 15:54:00 【Game programming】
Experimental environment preparation
create table stu (id int,name varchar(10)primary key not null,score decimal(5,2),address varchar(20),hobbid int(5));
insert into stu values(1,'zhao',100,'riben',2); insert into stu values(2,'qian',59.99,'taiguo',2); insert into stu values(3,'sun',75,'mianduan',3); insert into stu values(4,'li',99,'ouzhou',4); insert into stu values(5,'zhou',10,'huisuo',5); insert into stu values(6,'wu',11,'nanjin',3); insert into stu values(7,'zheng',80,'cv',3); insert into stu values(8,'wang',88,'cv',7);

One 、order by sentence
( increase 、 Delete 、 Change 、 check )
Yes MysQL Database query , In addition to basic queries , Sometimes you need to process the result set of the query . For example, take only 10 Data 、 Sort or group the query results, etc .
Sort by keyword
PS: Analogy to windows Task manager , Use SELECT Statement can transfer the required data from MySQL From the database , If you sort the results of the query , have access to ORDER BY Statement to sort statements , And finally return the sorted results to the user . The sorting of this statement can not only be for a certain field , You can also target multiple fields
grammar
SELECT column1,column2,... FROM table_name ORDER BY column1,column2,...---- ORDER BY ---- Sort by keyword Syntax :SELECT " Field " FROM " Table name " [WHERE " Conditions "] ORDER BY " Field " [ASC, DESC];#ASC It's sorted in ascending order , Is the default sort method .#DESC It's sorted in descending order .1、 Single field sorting
order by It can also be combined with where Perform conditional filtration , The screening address is cv Of the students are ranked in descending order of scores

2、 Sorting multiple fields
Statements can also use multiple fields to sort , When there are multiple records with the same field in the first sorting , These multiple records are sorted according to the second field ,ORDER BY
When followed by multiple fields , The fields are separated by English commas , Priority is in order, but order by The next first parameter is only when the same value appears , The second field makes sense .
Query student information by interest first id Descending order , With the same score ,id Also in descending order

Query student information by interest first id Descending order , With the same score , id In ascending order

Two 、 Ascending and descending (ASC and DESC)
ASC:
It's sorted in ascending order , Is the default sort method , namely ASC It can be omitted .SELECT If no specific sorting method is specified in the statement , By default ASC Sort by .

DESC:
Is arranged in descending order . Of course ORDER BY You can also use WHERE Clause to further filter the query results .

3、 ... and 、select Inquire about
---- SELECT ---- Displays all data syntax for one or more fields in the table :SELECT " Field " FROM " Table name ";1、 View all

2、 View some fields

Four 、and/or- And / or
---- AND OR ---- And Or grammar :SELECT " Field " FROM " Table name " WHERE " Conditions 1" {[AND|OR] " Conditions 2"}+ ;1、and

2、or

3、 nesting / Multiple conditions

5、 ... and 、distinct( Query does not duplicate records )
---- DISTINCT ---- Do not display duplicate data syntax :SELECT DISTINCT " Field " FROM " Table name ";SELECT DISTINCT Store_Name FROM Store_Info;
6、 ... and 、where
--- WHERE ---- Conditional query syntax :SELECT " Field " FROM " Table name " WHERE " Conditions ";
7、 ... and 、group by( Group results )
adopt SQL The result of the search , You can also group the total , Use GROUP BY Statement to implement ,GROUP BY Usually used in conjunction with aggregate functions , Common aggregation functions include : Count ( COUNT) 、 Sum up (SUM)、 Average (AVG)、 Maximum (MAX)、 minimum value (MIN),GROUP BY When grouping, the results can be grouped according to one or more fields .
grammar
SELECT column_name,aggregate_function (column_name)FROM table_name WHERE column_nameoperator valueGROUP BY column name;---- GROUP BY ---- Yes GROUP BY Summarize and group the query results in the following fields , Usually used in combination with aggregate functions GROUP BY There is a principle , Namely SELECT In all the following columns , Columns that do not use aggregate functions , Must appear in GROUP BY Back . grammar :SELECT " Field 1", SUM(" Field 2") FROM " Table name " GROUP BY " Field 1";1、 Press hobbid Same grouping , Calculate the number of students with the same score ( be based on name Count the number )

2、 combination where sentence , The filter score is greater than or equal to 80 The grouping , Count the number of students

3、 combination order by Arrange the number of students in ascending order
Transcript of the whole class count (name) :
Count score fraction :
score>=80 : good
score >=60 and score <80 : optimal -
select count(name),score,hobbid from stu where score >=80 group by hobbid ;select count(name),score,hobbid from stu where score >= 80 group by hobbid order by count(name) asc;

select count(name),score from stu where score > 80 group by score;
8、 ... and 、limit
Limit result entries ( limit )
limit Limit the result record of output
In the use of MySQL SELECT Statement to query , The result set returns all matching records ( That's ok ). Sometimes you just need to return the first line or the first few lines , And that's where it comes in LIMIT Clause .
grammar
SELECT column1,column2,... FROM table_name LIMIT [offset, ] number LIMIT The first parameter is the position offset ( Optional parameters ), It's settings MysQL Which line to start with . If the first parameter is not set , It will start from the first record in the table . It should be noted that , The position offset of the first record is 0, The second is 1, And so on . second : The first parameter is to set the maximum number of returned record rows .
Before all information is displayed 4 rows

combination order by sentence , Press id The first three lines are displayed in ascending order of size

Basics select How to output the last three lines for a small upgrade

Nine 、alias( Set alias )
Set alias ( alias ——》as )
stay MysQL When inquiring , When the name of the table is long or some fields in the table are long , For the convenience of writing or
Use the same table multiple times ," You can set aliases for fields, columns, or tables . Use aliases directly when using , Simple and clear , enhance readability
grammar
For column aliases :SELECT column_name AS alias_name FROM table_name; For table aliases :SELECT column_name (s)FROM table_name As alias_name; In the use of AS after , It can be used alias_name Instead of table_name, among AS The statement is optional .AS Later alias , It is mainly used to provide temporary names for columns or tables in the table , Use in the process of checking , The actual table name or segment name in the library will not be changed
Example of column alias setting :
select name as full name ,score as achievement from stu;
If the length of the table is long , have access to as Alias the table , In the process of query, the alias is directly used for temporary setting stu Its alias is i
select i.name as full name ,i.score as achievement from stu as i;
Inquire about stu Number of records in the table , With number Show



Use scenarios :
When querying complex tables , Aliases can shorten the length of query statements 2、 When querying multiple tables ( Easy to understand 、i Shorten sql sentence )
Besides ,as It can also be used as an operator of join statements .
establish t1 surface , take stu All query records of the table are inserted t1 surface
create table t1 as select * from stu;select * from t1
# here As What it does :
Created a new table t1 And define the table structure , Insert table data ( And info The table is the same )2、 however " constraint " Not completely " Copy “ To come over
# But if the primary key is set in the original table , Then the attached table : default The field will be set to one by default 0 be similar :
clone 、 Replicated table structure
create table t1 (select * from info);
# You can also join where Sentence judgment
create table test1 as select * from info where score >=60;
When setting an alias for a table , Make sure that the alias does not conflict with the names of other tables in the database .
The alias of the column is shown in the result , The alias of the table is not shown in the results , Use... Only when executing queries .
author : Long feeling cl
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
- Client development (electron) system level API usage
- 不要再「外包」AI 模型了!最新研究发现:有些破坏机器学习模型安全的「后门」无法被检测到
- Binocular 3D perception (I): preliminary understanding of binocular
- LeCun预言AGI:大模型和强化学习都是斜道!我的「世界模型」才是新路
- 不要小看了积分商城,它的作用可以很大!
- Leetcode topic [array]-34- find the first and last positions of elements in a sorted array
- 什么是NFT数字藏品?
- 基于深度Q学习的雅达利打砖块游戏博弈
- Native JS dynamically add elements
- Asynchronous processing of error prone points
猜你喜欢
Cloning and importing DOM nodes

Read the configuration, explain the principle and read the interview questions. I can only help you here...
Power representation in go language

Programmer vs hacker thinking | daily anecdotes

JVM memory region details

面试官:你简历上说精通mysql,那你说下聚簇/联合/覆盖索引、回表、索引下推
Introduction to database transactions

教务系统开发(PHP+MySQL)

基于神经标签搜索,中科院&微软亚研零样本多语言抽取式摘要入选ACL 2022

剑指 Offer 10- I. 斐波那契数列
随机推荐
Sword finger offer 04 Find in 2D array
sql优化的几种方式
Principle and implementation of MySQL master-slave replication (docker Implementation)
JS中的==和===的区别(详解)
Golang open source streaming media audio and video network transmission service -lal
For the first time in Chinese universities! Unique in the world! Tongji students win international awards
Continuously improve the overall performance of adaoracle Oracle Oracle
Continuous integration of aspnetcore & cloud flow
MySQL修改字段語句
剑指 Offer 10- I. 斐波那契数列
Differences and solutions of redis cache avalanche, cache penetration and cache breakdown
Source code analysis of nine routing strategies for distributed task scheduling platform XXL job
解决Visio和office365安装兼容问题
Linux-MySQL数据库之高级SQL 语句一
转换Cifar10数据集
Do you want to go to an outsourcing company? This article will give you a comprehensive understanding of outsourcing pits!
Introduction to database transactions
Don't underestimate the integral mall, its role can be great!
Desktop development (Tauri) opens the first chapter
Mapbox map - inconsistent coordinate system when docking GIS layers?