Home  >  Article  >  Database  >  【mysql】关于子查询的一个例子_MySQL

【mysql】关于子查询的一个例子_MySQL

WBOY
WBOYOriginal
2016-06-01 13:32:28850browse

bitsCN.com

【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'

 

希望得到结果为:

a  b  c

1  3  'cd'

2  3  'nhd'

3  7  'vsd'

 

(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);

 

由于是嵌套查询和取交集,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;

 

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

 

 

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

bitsCN.com
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