关闭

优化MySQL嵌套查询和联表查询

发表于:2013-2-28 11:34

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:afeiqiang 译    来源:51Testing软件测试网采编

  嵌套查询糟糕的优化

  在上面我提到过,不考虑特殊的情况,联表查询要比嵌套查询更有效。尽管两条查询表达的是同样的意思,尽管你的计划是告诉服务器要做什么,然后让它决定怎么做,但有时候你非得告诉它改怎么做。否则优化器可能会做傻事。我最近就碰到这样的情况。这几个表是三层分级关系:category, subcategory和item。有几千条记录在category表,几百条记录在subcategory表,以及几百万条在item表。你可以忽略category表了,我只是交代一下背景,以下查询语句都不涉及到它。这是创建表的语句:

create table subcategory (
    id int not null primary key,
    category int not null,
    index(category)
) engine=InnoDB;

create table item(
    id int not null auto_increment primary key,
    subcategory int not null,
    index(subcategory)
) engine=InnoDB;

  我又往表里面填入一些样本数据

insert into subcategory(id, category)
    select i, i/100 from number
    where i <= 300000;

insert into item(subcategory)
    select id
    from (
        select id, rand() * 20 as num_rows from subcategory
    ) as x
        cross join number
    where i <= num_rows;

create temporary table t as
    select subcategory from item
    group by subcategory
    having count(*) = 19
    limit 100;

insert into item (subcategory)
    select subcategory
    from t
        cross join number
    where i < 2000;

  再次说明,这些语句运行完需要一点时间,不适合放在产品环境中运行。思路是往item里插入随机行数的数据,这样subcategory就有1到2018之间个item。这不是实际中的完整数据,但效果一样。

  我想找出某个category中item数大于2000的全部subcategory。首先,我找到一个subcategory item数大于2000的,然后把它的category用在接下来的查询中。这是具体的查询语句:

select c.id
from subcategory as c
    inner join item as i on i.subcategory = c.id
group by c.id
having count(*) > 2000;

-- choose one of the results, then
select * from subcategory where id = ????
-- result: category = 14

31/3123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号