当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL嵌套查询实例详解

MySQL嵌套查询实例详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

两人力大冲破天打一字,恋清尘,琴帝txt小说下载

本文实例分析了mysql嵌套查询。分享给大家供大家参考,具体如下:

mysql从4.11版后已经完全支持嵌套查询了,那么下面举些简单的嵌套查询的例子吧(源程序来自mysql user manual):

1. select语句的子查询

语法:

复制代码 代码如下:
select ... from (subquery) as name ...

先创建一个表:

create table t1 (s1 int, s2 char(5), s3 float);
insert into t1 values (1,'1',1.0);
insert into t1 values (2,'2',2.0);

我们就可以进行以下的嵌套查询了:

select sb1,sb2,sb3
from (select s1 as sb1, s2 as sb2, s3*2 as sb3 from t1) as sb
where sb1 > 1;

结果是: 2, '2', 4.0.

我们知道下面语句是不会得到正确结果的,因为对经过group by排序的集合进行求均值是不能得到正确答案的:

复制代码 代码如下:
select avg(sum(column1)) from t1 group by column1

所以我们可以通过下面的嵌套查询实现同样的效果:

select avg(sum_column1)
from (select sum(column1) as sum_column1
from t1 group by column1) as t1;

2.行的子查询(row subquery)

看下面的例子:

复制代码 代码如下:
select * from t1 where row(1,2) = (select column1, column2 from t2);

这个查询是返回column1等于column2的结果行。row函数中的1和2相当于构造参数。想必blogjava上的同志对这些应该比较清楚,也不去详细介绍了。

3.使用exist和not exist参数

这里的exist和not exist用途及用法和在其他没有什么大的区别,我就简单举几个范例好了:

范例一:

select distinct store_type from stores
where exists (select * from cities_stores
where cities_stores.store_type = stores.store_type);

范例二:

select distinct store_type from stores
where not exists (select * from cities_stores
where cities_stores.store_type = stores.store_type);

范例三:  这个例子中嵌套使用了not exist语法,稍微注意一下:

select distinct store_type from stores s1
where not exists (
select * from cities where not exists (
select * from cities_stores
where cities_stores.city = cities.city
and cities_stores.store_type = stores.store_type));

4.条件关联关系查询

select column1 from t1 as x
where x.column1 = (select column1 from t2 as x
where x.column1 = (select column1 from t3
where x.column2 = t3.column1));

跟其他数据库做法是一样的。

5.其他使用方法和注意

除了上面这些还有很多很多,不过就不去细讲了,因为这些跟别的数据库差不多,只是为了给大家一个参考,提提就够了。

select (select s1 from t2) from t1;
select (select s2 from t1);

支持子查询的语法有:select,insert,update,delete,set和do。

子查询可以使用任何普通查询中使用的关键词:如dinstinct,group by,limit,order by,union,all,union all等。可以使用<,>, <=, >=, =, <>运算符进行比较,也可以使用any ,in和some进行集合的匹配。

希望本文所述对大家mysql数据库程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网