2017-03-19 99 views
0

查詢我旁邊表:提高越來越一行最大值

CREATE TABLE IF NOT EXISTS `Customers` (
    `id` INT AUTO_INCREMENT, 
    `name` VARCHAR(20) NOT NULL, 
    PRIMARY KEY(`id`) 
); 

CREATE TABLE IF NOT EXISTS `Orders` (
    `id` INT AUTO_INCREMENT, 
    `id_cust` INT NOT NULL, 
    `descr` VARCHAR(40), 
    `price` INT NOT NULL, 
    PRIMARY KEY(`id`), 
    FOREIGN KEY(`id_cust`) REFERENCES `Customers`(`id`) 
); 

一個客戶可以有多個訂單。我想得到id_cust和誰支付最多(一個人)的訂單的總和。 我的查詢:

SELECT cust, max_orders_sum 
FROM 
(
    (
     SELECT MAX(orders_sum) AS max_orders_sum 
     FROM (
      SELECT o.id_cust AS cust, SUM(o.price) AS orders_sum 
      FROM Orders AS o 
      GROUP BY o.id_cust 
     ) AS same_query0 
    ) AS step1 
    INNER JOIN 
    (
     SELECT o.id_cust AS cust, SUM(o.price) AS orders_sum 
     FROM Orders AS o 
     GROUP BY o.id_cust 
    ) AS same_query1 
    ON (step1.max_orders_sum = same_query1.orders_sum) 
); 

主要問題: 你可以看到,它具有相同的部分:same_query0same_query1。有什麼辦法可以擺脫它們嗎? 或者如果你知道更好的方式來達到我的目標,請分享。 我發現一個簡單的解決方案:

SELECT o.id_cust AS cust, SUM(o.price) AS orders_sum 
FROM Orders AS o 
GROUP BY o.id_cust 
ORDER BY orders_sum DESC LIMIT 1; 

但是,這不是解決問題的直接途徑。

回答

0

另一個在同一e很好的解決方案:

select id_cust, sum(price) from orders group by id_cust having sum(price) = 
(select max(prc) from 
(select sum(price) as prc from orders group by id_cust) as tb); 
0

我不認爲你可以做的比你已經做了好多了,除非你創建了

create view v_cust_tot as 
select id_cust, sum(price) as cust_tot 
from Orders 
group by id_cust 

有了一個視圖你可以重寫查詢這樣

select id_cust, cust_tot 
from v_cust_tot 
where cust_tot = (select max(cust_tot) from v_cust_tot) 

這將是一個進步只是在查詢的緊湊性,因爲我覺得表演是作爲執行計劃將是幾乎相同