Home > Database > Mysql Tutorial > body text

MySQL子查询用法实例分析_MySQL

PHP中文网
Release: 2016-05-27 13:44:34
Original
1039 people have browsed it

本文实例讲述了MySQL子查询用法。分享给大家供大家参考,具体如下:

假设表my_tbl包含三个字段a,b,c;现在需要查询表中列a的每个不同值下的列b为最小值的记录量。

比如表记录为:

a  b  c
1  3  'cd'
2  3  'nhd'
1  5  'bg'
2  6  'cds'
1  7  'kiy'
3  7  'vsd'
3  8  'ndf'
Copy after login

希望得到结果为:

a  b  c
1  3  'cd'
2  3  'nhd'
3  7  'vsd'
Copy after login

(1) 其中一个做法:先查出每个a值下的b最小值,然后根据这些最小值去查询符合要求的所有记录。

查询符合最小b值的sql写法如下:

代码如下:

select A.* from my_tbl as A where A.b=(select min(b) from my_tbl as B where B.a=A.a);
Copy after login

由于是嵌套查询和取交集,80万条记录情况下竟然用一个小时也没把中间结果算出来(我真怀疑是自己哪里写错了);后面求记录量就免谈了。

(2) 上面的方法是个灾难, 只能弃用了。

具体逻辑为:先按列a,b分组,然后选择每组中列b值最小的记录,生成结果集。

sql语句写法如下:

代码如下:

select a,b,c,count(a) from (select a,b,c from my_tbl group by a,b) as A group by a;
Copy after login

执行查询后,时间竟只用了1.1秒。

再一次证明,sql的查询策略的不同能直接导致性能上的巨大差异。

 以上就是MySQL子查询用法实例分析_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!