网站建设知识
MySQL自学笔记4
2025-07-22 11:13  点击:0

MySQL自学笔记

使用MySQL 5.5以及MySQL自带命令客户端

子查询

定义:一个查询是另外一个查询的条件时,称为子查询。子查询就是在原有的查询语句中,嵌入新的查询,来得到想要的结果集。根据子查询的嵌入位置,可以分为三种子查询:where型子查询、from型子查询、exists型子查询

where型子查询

将内层查询的结果作为外出查询的比较条件
典型的语法:

select * from table1Namewhere colName = (select colName from table2Name where ...)# 上面的table1Name和table2Name可以是一样的,也可以是不一样的# 上面的句子中等号相当于符号in,如下:# where colName in (select colName from table2Name where ...)

举一个例子:存在一个goods表,查询里面最新商品、最贵商品

select goods_id, goods_namefrom goodswhere goods_id = (select max(good_id) from goods);# 查询出最新的商品
select goods_id, goods_name, shop_price from goodswhere shop_price in (select max(shop_price) from goods group by cat_id);

from型子查询

将内层的查询结果当作临时表,供给外出的SQL语句进行再次查询。可以给临时表起一个别名,用关键字as
典型的语法:

select * from (select * from  table1Name where ...) where ...

举一个例子:有一张成绩表stu,查询两门及两门以上不及格同学的平均分

select name, avg(socre) from stu where name in (select name from (select name, sum(score < 60) as temp1 from stu group by name having temp1 > 1) as temp2) group by name;

exists型子查询

将外层的查询结果拿到内层,看内层的查询是否成立。该查询实际上不返回任何的数据,而是返回True或False。该查询可以与in型子查询互换,但是该查询效率高。
典型的语句:

select * from table1Namewhere exists (select * from table2Name where ..)

举一个例子:对于goods表和category表,查询有商品的栏目

select cat_id, cat_name from category where exists (select * from goods where goods.cat_id = category.cat_id);