我试图加入两张桌子,并且还得到一个SUM并且非常糟糕。我需要获得每个会员的总佣金金额,其中affiliate.approved = 1 AND order.status = 3.
//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 :(得分: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;
答案 1 :(得分: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;
答案 2 :(得分: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;
警告:您选择了一个MySQL的保留字作为表名(order
)。请注意始终用(`)反引号将其括起来。
只是一个温和的提醒
答案 3 :(得分: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的关键词,我建议你不要将它用作表/列名。