search
HomeDatabaseMysql TutorialSummarize and share 15 commonly used query clauses in MySQL (come and collect them)

How to query in MySQL? The following article summarizes and shares 15 commonly used query clauses in MySQL, which are worth collecting. I hope it will be helpful to everyone!

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

For data analysis, MySQL mostly uses queries, such as data sorting, grouping, deduplication, summary, string matching, etc. If the queried data involves multiple tables, you need to join these tables. This article will talk about the commonly used query clauses in MySQL, a total of 15. [Related recommendations: mysql video tutorial]

*1, *Sort: order by

Sort is by order Implemented, for example, to query data from the StuInfo table and sort it by age. The sql statement is:

select * from stuinfo order by age;

Query results:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

As you can see, the query results are arranged in ascending order according to age. If you want to achieve descending order, just You need to add desc at the end. The sql statement is:

select * from stuinfo order by age desc;

Query results:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

The query results at this time are arranged in descending order by age.

The above is for sorting numerical data. If it is a string, you can also use order by to sort. For example, to sort by name, the sql statement is:

select * from stuinfo order by stuname;

Query result:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

As you can see from the above, string sorting is actually sorting in ascending order according to the first letter. Of course, you can also sort dates, please think about it yourself.

*2, *Group: group by

Grouping is implemented through the group by clause. For example, to group by gender, the sql statement is.

select gender,count(*) from stuinfo group by gender;

Query results:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

The above SQL statements are grouped by gender and give the number of people in each group. Grouping by other fields is also similar.

*3, *Deduplication: distinct

Deduplication is a common operation in data processing, which is implemented through the distinct clause, such as query All cities where students are located need to be duplicated because some students are in the same city.

sql statement is:

select distinct city from stuinfo;

Query result:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

As you can see, deduplication is to add distinct before the deduplication field That’s it.

*4, *Null value: is null/is not null

Null value is to determine whether a field is empty or not empty For example, to query the records whose city is empty, the sql statement is:

select * from stuinfo where city is null;

Query results:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

You can see that the query is empty records In fact, it is the where condition followed by is null.

Conversely, if you query for records where the city is not empty, just follow is not null. The sql statement is:

select * from stuinfo where city is not null;

Query results:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

*5, *Summary: counting, maximum value, sum, mean value

Summary is actually counting, finding the maximum/minimum value, Sum, average, etc.

How many records are in the most commonly used statistical table, implemented through count, the sql statement is:

select count(*) from stuinfo;

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

Query the maximum value of a field in the table/ The minimum value is achieved through max/min. For example, to query the maximum age, the sql statement is:

select max(age) from stuinfo;

Query results:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

The next question: Query How to write the name of the oldest student in SQL statement?

This is a conditional query. The condition is that the age must be equal to the maximum age. According to this idea, write the sql statement:

select stuname,age from stuinfo where age=(select max(age) from stuinfo);

Query result:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

As you can see from the above, the oldest age is actually queried as a condition, and then the corresponding name and age are queried.

Leave a question: How to query the name of the youngest student?

To sum, just use sum. It must be a sum of numerical data, similar to count. This will not be demonstrated.

The last is the mean value, use avg, for example, to query the average age of all students, the sql statement is:

select avg(age) from stuinfo;

Query results:

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

*6、 *别名:as

别名,就是as,意为用作,例如,查询出年龄的最大值、最小值和均值,sql语句为:

select max(age),min(age),avg(age) from stuinfo;

查询结果:

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

这样显示字段名不太好看,我们可以用as起一个别名,sql语句为:

select max(age) as age_max,min(age) as age_min,avg(age) as age_avg from stuinfo;

查询结果:

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

*7、 *表的连接

当要查询的记录涉及两个或者两个以上的表时,就需要表的连接。

表的连接有三种:内连接、左连接和右连接。

(1)内连接:inner join

内连接相当于两个表的交集,如下图所示。

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

例如,有两个表:学员信息表和成绩表,有一个共同的列:学号。

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

现在想查询出每个学员的姓名和成绩,查询结果如下图所示。

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

以上查询结果中的姓名需要从第一个表中提取,成绩需要从第二个表中提取,这叫表的连接

因为学号是共同的列,所以根据学号连接,以上的这种连接方式是获取两个表中学号相同的记录,叫作内连接

具体的sql语句为:

select sname,score fromtb1 inner join tb2 on tb1.sid=tb2.sid;

查询结果:

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

需要注意的是,连接条件用on。

(2)左连接:left join

左连接是以左表为基准,去匹配右表中的记录,如果右表中没有对应匹配记录则为空。

左连接用集合中的文氏图表示如下。

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

还是用以上提到的学员信息表和成绩表,左连接的示意图如下。

1Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

左连接的sql语句为:

select sname,score fromtb1 left join tb2 on tb1.sid=tb2.sid;

查询结果:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

(3)右连接:right join

右连接是以右表为基准,去匹配左表中的记录,如果左表中没有对应匹配记录则为空。

右连接用集合中的文氏图表示如下。

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

还是用以上提到的学员信息表和成绩表,右连接的示意图如下。

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

右连接的sql语句为:

select sname,score fromtb1 right join tb2 on tb1.sid=tb2.sid;

查询结果:

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

*8、 *字符串匹配:like

有时候在字符串查找时,需要查找符合某个匹配模式的字符串。

例如,在表stuinfo中,查找城市中含有字符串‘an’的记录,sql语句为:

select * from stuinfo where city like '%an%';

注意:匹配模式中的%表示匹配任意长度的任意字符串。

*9、 *集合:in

查找属于某个集合的记录用in。

例如,查找城市为北京或者天津的记录,sql语句为:

select * from stuinfo where city in('Beijing','Tianjin');

查询结果:

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

*10、 *条件语句:having

这里说的条件语句是having,跟where类似,但是一般和统计函数连用。

比如,查找平均年龄小于25岁的城市,sql语句为:

select city from stuinfo group by city having avg(age)<25;

查询结果:

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

以上sql语句先按照城市分组,再跟条件语句having。

*11、 *区间查找:between and

between and用于查找符合某个区间(包含两个边界的值)的记录。

例如,查找年龄介于20到30岁之间的记录,sql语句为:

select * from stuinfo having age between 20 and 30;

查询结果:

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

*12、 *联结:union

联结,也叫联合,用于连接两个查询的结果,并且去重。

例如,两个表中都有学号,用sql语句分别从这两个表中查询出学号,然后联结。

select sid from tb1unionselect sid from tb2;

查询结果:

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

以上sql语句相当于将两个select语句的查询结果用union合并,并且是去重合并。

如果不想去重,用union all即可,sql如下。

select sid from tb1union allselect sid from tb2;

查询结果:

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

*13、 *日期格式化:date_format

在SQL中,对于日期时间的处理也是很常见的问题。

例如,按照年份、月份或者日期等对数据进行分组汇总,就需要从日期时间中提取年份、月份及日期等。

举个例子,获取每个学员的出生年份,sql语句为:

select date_format(birthdate,&#39;%Y&#39;) as birth_year from stuinfo;

查询结果:

2Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

获取出生月份也是如此,只是参数用'%m',sql语句为:

select date_format(birthdate,&#39;%m&#39;) as birth_year from stuinfo;

查询结果:

Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

获取到年份、月份后,就可以按照年份、月份进行分组查询统计了。

*14、 *条件分支:case语句

条件分支是数据统计中的一个很重要的应用,在MySQL中用case语句表达条件分支,case语句有以下两种用法。

用法一:

例如,根据学员所处的城市,将记录标记为一线城市及其他,sql语句为:

select distinct city,
  case city
    when &#39;Beijing&#39; then &#39;一线城市&#39;
    when &#39;Shanghai&#39; then &#39;一线城市&#39;
    else &#39;其他&#39; end as city_level
from stuinfo;

查询结果:

3Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

从上面看到,case后面跟的是要判断的字段,when后跟的是不同的情况,then则是不同情况对应的类别,最后的else表示其他情况。

整个case语句相当于给原来的表增加一个字段:city_level,然后我们可以根据这个字段进行分组查询。

用法二:

例如,根据学员的年龄进行分层,青年、中年及其他,sql语句为:

select stuname,age,
  case when age<30 then &#39;青年&#39;
      when age>=30 and age<35 then &#39;中年&#39;
      else &#39;其他&#39; end as age_level
from stuinfo;

查询结果:

3Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

从上面可以看到,case后面跟的是条件when,即年龄满足什么条件时,将其划分到对应的类别,最后的else表示其他情况。

整个case语句相当于给原来的表增加一个字段:age_level,然后我们可以根据这个字段进行分组查询。

*15、 *变量

最后,谈谈MySQL中的变量,当然,MySQL中的变量有好几种类型,这里只说用户变量,像@var这种。

例如,我们希望根据学员的年龄计算出每个人到35岁还有几年,这里可以定义一个变量并赋值为35,然后利用这个变量减去年龄就得到结果。

首先,定义变量var,sql语句为:

set @var:=35;

接着,使用这个变量,sql语句为:

select @var-age as age_gap from stuinfo;

查询结果:

3Summarize and share 15 commonly used query clauses in MySQL (come and collect them)

当然,关于变量还有很多更复杂的用法,多用于计算连续登陆天数这种问题或者存储过程中。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Summarize and share 15 commonly used query clauses in MySQL (come and collect them). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software