2016-07-27 175 views
0

我試圖連接兩個表,並且還得到了一個SUM,並且引起了嚴重的反應。我需要獲得每個子公司的佣金總額,其中affiliate.approved = 1 AND order.status = 3。mysql:兩個表的連接總和

//affiliate table 
affiliate_id | firstname | lastname | approved | 
    1   joe  shmoe  1 
    2   frank  dimag  0 
    3   bob  roosky  1 

這裏的順序表

//order 
affiliate_id | order_status_id | commission 
    1    3    0.20 
    1    0    0.30 
    2    3    0.10 
    3    3    0.25 
    1    3    0.25 
    2    3    0.15 
    2    0    0.20 

,這裏是我想查詢返回的內容:

affiliate_id | commission 
    1    0.45 
    3    0.25 

這裏是我的嘗試不起作用。它只輸出一行。

SELECT order.affiliate_id, SUM(order.commission) AS total, affiliate.firstname, affiliate.lastname FROM `order`, `affiliate` WHERE order.order_status_id=3 AND affiliate.approved=1 AND order.affiliate_id = affiliate.affiliate_id ORDER BY total; 

感謝您的任何幫助。

回答

0

你已經錯過了GROUP BY,試試這個:

SELECT 
     `order`.affiliate_id, 
     SUM(`order`.commission) AS total, 
     affiliate.firstname, 
     affiliate.lastname 
FROM `order` 
JOIN `affiliate` 
ON `order`.order_status_id = 3 AND affiliate.approved = 1 AND `order`.affiliate_id = affiliate.affiliate_id 
GROUP BY `order`.affiliate_id 
ORDER BY total; 

Demo Here

+0

這個解決方案也工作得很好。 –

0

你可以試試這個查詢您的解決方案: -

SELECT order.affiliate_id, SUM(order.commission) AS total,affiliate.firstname, 
    affiliate.lastname 
    FROM `order`, `affiliate` 
    WHERE order.order_status_id=3 
    AND affiliate.approved=1 
    AND order.affiliate_id = affiliate.affiliate_id 
    GROUP BY order.affiliate_id 
    ORDER BY total; 
+0

此解決方案也工作正常。 –

0

第一:刪除隱含join句法。這很混亂。

第二個:您需要按affiliate_id分組。使用不帶組的聚合函數將結果集摺疊爲單行。

下面是一個使用INNER JOIN查詢:

SELECT 
    `order`.affiliate_id, 
    SUM(`order`.commission) AS total, 
    affiliate.firstname, 
    affiliate.lastname 
FROM `order` 
INNER JOIN`affiliate` ON `order`.affiliate_id = affiliate.affiliate_id 
WHERE `order`.order_status_id = 3 
AND affiliate.approved = 1 
GROUP BY affiliate.affiliate_id 
ORDER BY total; 

WORKING DEMO

注意:您已選擇了MySQL的保留字作爲表名(order)之一。注意用(`)總是反向附加它。

只是一個善意提醒

+0

這很好。 –

0

這裏是解決方案:

select affiliate.affiliate_id,sum(`order`.commission) as total from affiliate left join `order` on affiliate.affiliate_id=`order`.affiliate_id 
where affiliate.approved=1 and `order`.order_status_id=3 group by affiliate.affiliate_id 

此外,「訂單」是SQL的一個關鍵的詞,我建議你不要使用它作爲一個表/列名稱。