当主表与另一个manyToOne关系表联接时,该字段的SUM相乘

时间:2019-02-20 17:47:41

标签: mysql laravel

select sum(t.amount) user_amount_sum 
  from users u
  join investor_transactions t
    on u.id = t.investor_id
 group 
    by u.id;

为每个用户返回user_amount_sum值40。 (正确)

  

从中选择总和(investor_transactions.amount)AS user_amount_sum   {{1}上的users 内部加入merchant_usermerchant_user =   user_id上的usersid 内部联接investor_transactionsusers =   idinvestor_transactionsinvestor_id分组。users;

但是现在为每个用户返回user_amount_sum值200。 (是其他用户的5倍,merchant_user表中有5行)

注意1:两个查询之间的唯一区别是

id

NB 2:我要加入merchant_user表以进行过滤。

解决此问题的最佳做法是什么??

1 个答案:

答案 0 :(得分:1)

SUM和所有聚合函数对(FROM ... WHERE的)中间结果进行操作;任何时候加入多个1:N关系,您都会遇到此问题。由于您仅使用其他联接进行过滤,因此您应该能够使用以下替代方法:

SELECT SUM(investor_transactions.amount) AS user_amount_sum 
FROM users 
INNER JOIN investor_transactions ON users.id = investor_transactions.investor_id 
INNER JOIN (SELECT DISTINCT user_id FROM merchant_user) AS mu ON mu.user_id = users.id 
GROUP BY users.id;

SELECT SUM(investor_transactions.amount) AS user_amount_sum 
FROM users 
INNER JOIN investor_transactions ON users.id = investor_transactions.investor_id 
WHERE users.id IN (SELECT DISTINCT user_id FROM merchant_user) 
GROUP BY users.id;

SELECT SUM(investor_transactions.amount) AS user_amount_sum 
FROM users AS u
INNER JOIN investor_transactions ON u.id = investor_transactions.investor_id 
WHERE EXISTS (SELECT * FROM merchant_user AS mu WHERE mu.user_id = u.id) 
GROUP BY users.id;

编辑:尽管我现在看了一下,但是您可能会跳过users表,因为您只使用了它的id字段,就像这样...

SELECT SUM(t.amount) AS user_amount_sum 
FROM investor_transactions AS t
INNER JOIN (SELECT DISTINCT user_id FROM merchant_user) AS mu ON t.user_id = mu.user_id
GROUP BY t.user_id;

,与上述其他替代方法类似。