MySQL嵌套选择查询性能

时间:2014-03-14 08:14:38

标签: mysql sql performance nested profiling

这两个查询之间有区别吗?像性能问题等?

查询1:

select  i.invoice_id,
        i.total_price
  from ( select invoice_id, 
                sum(price) as total_price 
           from orders
         group by 
                invoice_id
        ) as i 
               inner join invoice 
                   ON i.invoice_id = invoice.invoice_id

查询2:

select invoice.invoice_id,
       orders.total_price 
  from invoice
       inner join ( select invoice_id, 
                           sum(price) as total_price 
                      from orders
                    group by 
                           invoice_id
                    ) orders 
           ON orders.invoice_id = invoice.invoice_id

谢谢!

3 个答案:

答案 0 :(得分:0)

您的第一个查询

select  i.invoice_id,
        i.total_price
  from ( select invoice_id, 
                sum(price) as total_price 
           from orders
         group by 
                invoice_id
        ) as i 
               inner join invoice 
                   ON i.invoice_id = invoice.invoice_id

的结果相当于:

select invoice_id, 
     sum(price) as total_price 
from orders
group by invoice_id

答案 1 :(得分:0)

要获得相同的结果(如果invoice_id表中存在orders的所有invoice),则无需加入Invoice表,只需使用查询:

select invoice_id, 
       sum(price) as total_price 
from orders
      group by invoice_id

答案 2 :(得分:0)

让我在没有任何改变的情况下重写您的查询:

查询1

SELECT i.invoice_id,
       i.total_price
  FROM invoice INNER JOIN (
                           SELECT invoice_id, 
                                  sum(price) AS total_price 
                             FROM orders
                           GROUP BY 
                                  invoice_id
                           ) AS i 
                   ON i.invoice_id = invoice.invoice_id;

查询2:

SELECT invoice.invoice_id,
       i.total_price 
  FROM invoice INNER JOIN (
                           SELECT invoice_id, 
                                  sum(price) AS total_price 
                             FROM orders
                           GROUP BY 
                                  invoice_id
                           ) AS i 
                   ON i.invoice_id = invoice.invoice_id;

我改变的事情:

  • JOIN的顺序(无关紧要,因为它是INNER
  • 表别名(ordersi,我真的不明白,为什么要用不同的名称命名呢)

现在,显而易见的是,它们之间的唯一区别 - 主SELECT中的第一个参数。您的问题可能已经成功(如果一列上有索引而另一列不存在,并且根据查询,您不会总是同时使用orders.invoice_idinvoice.invoice_id),但因为你已经检索了INNER JOIN的两列,所以它没有。

此外,这些查询是多余的。正如@valex已经提到的那样,你的查询(实际上 - 两者都可以)(并且必须)简化为:

SELECT invoice_id, 
       sum(price) AS total_price 
  FROM orders
GROUP BY 
       invoice_id;

所以,不,性能没有差异。当然,结果集没有区别 此外,我希望您知道,您始终可以使用EXPLAIN来提供性能问题。