2016-07-27 177 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的一个关键的词,我建议你不要使用它作为一个表/列名称。