这两个查询之间有区别吗?像性能问题等?
查询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
谢谢!
答案 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
)orders
到i
,我真的不明白,为什么要用不同的名称命名呢)现在,显而易见的是,它们之间的唯一区别 - 主SELECT
中的第一个参数。您的问题可能已经成功(如果一列上有索引而另一列不存在,并且根据查询,您不会总是同时使用orders.invoice_id
和invoice.invoice_id
),但因为你已经检索了INNER JOIN
的两列,所以它没有。
此外,这些查询是多余的。正如@valex已经提到的那样,你的查询(实际上 - 两者都可以)(并且必须)简化为:
SELECT invoice_id,
sum(price) AS total_price
FROM orders
GROUP BY
invoice_id;
所以,不,性能没有差异。当然,结果集没有区别
此外,我希望您知道,您始终可以使用EXPLAIN
来提供性能问题。