1
select id,firstname,lastname,email,country,portal,language 
from totaluser 
where userid in 
    (select user from (select user, shipping / NULLIF(goodsvalue,0) as difference 
    from shipment 
    where user in 
        (select user 
        from (select user, count(*) as shipcount 
        from shipment 
            where user in 
            (select user from shipment 
            where status in ('3','5') 
            and createdtime between '2012-01-01' 
            and '2013-02-22' group by user) 
            and status in ('3','5') group by user) 
            as a 
        where status in ('3','5') 
        and shipcount=1)) 
    as b 
    where difference > 2.5);

我知道这是一个非常简单的语句,它可以立即在我的测试服务器中运行,但是在我的生产服务器中运行需要很长时间。我应该如何改变它以加快速度?

4

2 回答 2

1

您的查询看起来很混乱。如果我理解正确,它会这样做:

SELECT id,firstname,lastname,email,country,portal,language FROM totaluser LEFT JOIN
(SELECT user,COUNT(*) AS shipcount FROM shipment
 WHERE
    createdtime BETWEEN '2012-01-01' AND '2013-02-22' AND
    status IN ('3','5') AND
    shipping / NULLIF(goodsvalue,0) > 2.5
    GROUP BY user) AS condid
ON totaluser.id=condid.user
WHERE condid.shipcount = 1;

(你可以用这个小提琴来测试我是否正确)

我建议您使用CREATE INDEXuser为上的列shipment建立索引,并且通常还为 where 子句(id、status 和 createdtime)中涉及的任何其他列创建索引。这应该会加快大表上的选择查询(但会减慢写入速度,因此如果您的应用程序是写入密集型的,则必须找到折衷方案)。

于 2013-02-26T10:06:34.920 回答
1

试试这个查询

select tu.id, tu.firstname, tu.lastname, tu.email, tu.country, tu.portal, tu.language 
from totaluser tu, 
(select user 
     from shipment 
     where status in ('3','5') 
     and createdtime between '2012-01-01' 
     and '2013-02-22' and status in ('3','5')
     group by user 
     HAVING count(*) = 1 AND shipping / NULLIF(goodsvalue,0) > 2.5) s
where tu.userid = s.user;

我试图删除您从发货表中创建的子查询嵌套,并创建了一个与 totaluser 表连接的对象集合。

于 2013-02-26T09:33:20.607 回答