加快mysql内部查询速度

时间:2014-03-04 13:42:49

标签: mysql

我目前有:

SELECT ads, id as mid, (SELECT IFNULL(SUM(amount),0) FROM trans WHERE paidout=0 AND user_id=mid) as amount FROM accounts

我怎样才能执行内部求和查询然后通过它并以相同的方式组合余额?

3 个答案:

答案 0 :(得分:0)

将为返回的每一行执行子查询。如果将其转换为LEFT JOIN,它将被执行一次并且速度会非常快。

SELECT
  ads,
  id AS mid,
  COALESCE(amount, 0) AS amount
FROM
  accounts
  LEFT JOIN (
    /* Subquery returns SUM(amount) per user_id */
    /* LEFT JOIN in case there are no matching records */
    SELECT user_id, SUM(amount) AS amount
    FROM trans
    WHERE paidout = 0  
    GROUP BY user_id
  ) amt ON accounts.id = amt.user_id

SUM()也可以在您的案例的外部查询中完成,将GROUP BY应用于所有其他列。

SELECT 
  accounts.ads, 
  accounts.id AS mid
  COALESCE(SUM(amount), 0) AS amount
FROM
  accounts
  LEFT JOIN trans ON accounts.id = trans.user_id
WHERE trans.paidout = 0
GROUP BY
  accounts.ads,
  mid

答案 1 :(得分:0)

这样的事情应该有效:

SELECT ads, accounts.id as mid, ifnull(sum(amount),0) as amount
FROM accounts
LEFT JOIN trans ON paidout=0 AND user_id=accounts.id
GROUP BY accounts.id

答案 2 :(得分:0)

这将只有两个选择VS(1+(数量的行数))选择,就像你今天所做的那样。

select ads, mid, IFNULL(SUM(amount),0) as total
from (
    SELECT a.ads, a.id as mid, amount
    from accounts a
    join trans t on t.user_id = a.id and t.paidout = 0
)
group by ads, mid