2016-07-27 25 views
0

私は2つのテーブルを結合しようとしていますが、SUMを取得してひどく壊れてしまいます。 affiliate.approved = 1、order.status = 3の各アフィリエイトの手数料総額を取得する必要があります。mysql:合計で2つのテーブル結合

//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 

は動作しません、私の試みです。 1行だけを出力します。任意の助けを借りていただきありがとうございます。

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を削除します構文。ややこしい。

第2:あなたは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

注意:あなたは、テーブル名(order)としてMySQLの予約語のいずれかを選びました。常にそれを( `)バックティックで囲むことに注意してください。ただ、優しいリマインダー

+0

これはうまくいった。 –

0

ここで解決され

:、「順序」はSQLのキーワードに加えて

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 

ですが、私はテーブルとしてそれを使用しないことをお勧めします/列名。

関連する問題