search
HomeDatabaseMysql Tutorial详解MySQL中的分组查询与连接查询语句_MySQL

详解MySQL中的分组查询与连接查询语句_MySQL

分组查询 group by
group by 属性名 [having 条件表达式][ with rollup]
“属性名 ”指按照该字段值进行分组;“having 条件表达式 ”用来限制分组后的显示,满足条件的结果将被显示;with rollup 将会在所有记录的最后加上一条记录,该记录是上面所有记录的总和。

1)单独使用
group by 单独使用,查询结果只显示一个分组的一条记录。
实例:

select * from employee group by sex;

将只显示男女两条记录。

2)与group_concat()函数一起使用
每个分组中指定字段值都显示出来
实例:

select sex,group_concat(name) from employee group by sex;

显示结果中“女”会显示所有sex为“女”的名字name

sex | group_concat(name)
女 | 小红,小兰
男 | 张三,王五,王六

3)与集合函数一起使用
实例:

select sex,count(sex) from employee group by sex;

结果:

sex | count(num)
女 | 1
男 | 3

count()为计算个数的方法。

4)与having一起使用
“having条件表达式”,可以限制输出结果。只有满足条件表达式的结果才显示。
实例:

select sex,count(sex) from employee group by sex having count(sex) >= 3;

结果:

sex | count(sex)
男 | 3

“having条件表达式”作用于分组后的记录。

5)按多字段进行分组

select * from employee group by d_id,sex;

查询结果先按d_id分组,再按sex进行分组

6) 与with rollup一起使用
使用with rollup将会在所有记录的最后加上一条记录,这条记录是上面所有记录的总和
实例:

select sex,count(sex) from employee group by sex with rollup;

结果:

sex | count(sex)
女 | 1
男 | 5
null | 6

如果是字符串的话,比如姓名就会生成“张三,李四,王五”这种类型的结果,即name总和。

连接查询
将两个及两个以上的表连接起来选取所需数据。

1)内连接查询:
当两个表中具有相同意义的字段值相等时,就查询出该条记录。
实例:

代码如下:

select num,name,employee.d_id,age,d_name from employee,department where employee.d_id = department.d_id

因字段名相同,所以取d_id字段值时最好指定哪张表的字段。

2)外连接查询
select 属性名列表 from 表名1 left|right join 表名2 on 表名1.属性名1=表名2.属性名2;
左连接查询:
进行左连接查询时,可以查出表名1中所指的表中所有记录。而表名2所指表中,只能查询出匹配的记录。
实例:

代码如下:

select num,name,employee.d_id,age,d_name from employee left join department on 
employee.d_id = department.d_id;

右连接查询:
与左连接相反,可以查询出表名2中的的所有记录,而表名1中所指的表中,只查询出匹配的记录。

PS:使用集合函数查询
集合函数包括count(),sum(),avg(),max()和min()。
1)count()函数
统计记录条数
实例:

select count(*) from employee;

与group by一起使用

select d_id,count(*) from employee group by d_id;

上述语句会先分组后统计

2) sum()函数
sum()函数是求和函数
实例:

select num,sum(score) from grade where num= 1001;

select num,sum(score) from grade group by num;

sum()只能计算数值类型字段。
3)avg()函数
avg()函数是求平均值函数。
实例:

select avg(age) from employee;

select course,avg(score) from group by course;

4)max(),min()函数
求最大值和最小值。
实例:

select max(age) from employee;
select num,course,max(score) from grade group by course;

对于字符串的最大值问题,max()函数是使用字符对应的ascii码进行计算的。

以上就是详解MySQL中的分组查询与连接查询语句_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.