[英]DISTINCT SUM with MysQL JOIN
I have two tables tableA and tableB. 我有两个表tableA和tableB。
tableA
-------
ID sid amount
1 swerdd 20
2 swerdd 30
3 fdff 40
tableB
------
new_id token date
10 swerdd 2014 -10-12
11 swerdd 2014 -10-13
12 swerdd 2014 -10-13
Now when I use the query 现在当我使用查询
SELECT * FROM tableA JOIN tableB on tableA.sid = tableB.token
is giving multiple rows and so my other query 给多行,所以我的其他查询
SELECT SUM(amount) FROM tableA JOIN tableB on tableA.sid = tableB.token
is giving wrong results. 给出错误的结果。 How can I select the DISTINCT SUM ?
如何选择DISTINCT SUM?
EDIT : The thing is that I have a many to many relation here as the sid and token is repeating. 编辑:事情是,随着sid和token的重复,我在这里有很多对很多的关系。 So in a nutshell the question is how can I calculate distinct sum in a many to many join
简而言之,问题是如何在多对多连接中计算不同的和
A couple of approaches that don't involve a join operation... 几种不涉及联接操作的方法...
An EXISTS
predicate... 一个
EXISTS
谓词...
SELECT SUM(a.reward_amount)
FROM tableA a
WHERE EXISTS (SELECT 1 FROM tableB b WHERE b.token = a.sid)
An IN (subquery)
predicate... 一个
IN (subquery)
谓词...
SELECT SUM(a.reward_amount)
FROM tableA a
WHERE a.sid IN (SELECT b.token FROM tableB b)
For a join operation, one option is to use an inline view to get a distinct list of token... 对于联接操作,一种选择是使用内联视图来获取令牌的不同列表...
SELECT SUM(a.reward_amount)
FROM tableA a
JOIN ( SELECT b.token
FROM tableB b
GROUP BY b.token
) c
ON c.token = a.sid
To get distinct sum you can use below query 要获得不同的总和,您可以使用以下查询
SELECT reward_amount
FROM tableA
JOIN tableB on tableA.sid = tableB.token
GROUP BY reward_amount;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.