Mysql从另一个表中求和

时间:2017-07-28 16:09:27

标签: mysql sql database

我有一个数据库,每个用户都有一个uid,但每次都可以使用不同的昵称登录(表A)。现在用户可以购买东西,我正在保存登录ID和价格(表B)。我做了一个例子,请注意Nick和NickRenamed是同一个人,因为他们有相同的uid

表A

id  |  nickname   |  uid
1   | Nick        |  abcdef
2   | Nack        |  ab1234
3   | NickRenamed |  abcdef

表B

id  |  idA  | price
1   |   1   |   200
2   |   1   |   400
3   |   2   |    20
4   |   3   |    75

对于统计数据,我想得到每个(不同的)uid,最新的昵称,并总结该用户的价格

uid    | nickname    |  price_total
abcdef | NickRenamed |   675
ac1234 | Nack        |    20

我的approch

SELECT DISTINCT(A.uid)
     , A.id
     , A.nickname
     , SUM(B.price) 
  FROM A 
  JOIN B 
    ON A.id = B.idA 
 GROUP 
    BY A.uid

但是会抛出错误

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated 
column 'test.A.id' which is not functionally dependent on columns in 
GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

4 个答案:

答案 0 :(得分:0)

您需要两个单独的查询。

首先找出每个用户的总和

SELECT uid, SUM(price) as total
FROM TableA TA
JOIN TableB TB
  on Ta.id = Tb.idA
GROUP BY uid

现在获取每个用户的最新名称。

SELECT nickname, uid
FROM TableA T1
LEFT JOIN TableA T2
  ON T1.id > T2.id
 AND T1.uid = T2.uid
WHERE T2.id IS NULL

现在把两者放在一起

 SELECT step1.uid, 
        step2.nickname,
        step1.total

 FROM (    SELECT uid, SUM(price) as total
           FROM TableA TA
           JOIN TableB TB
             on Ta.id = Tb.idA
           GROUP BY uid) as step 1
 JOIN (    SELECT nickname, uid
           FROM TableA T1
           LEFT JOIN TableA T2
             ON T1.id > T2.id
            AND T1.uid = T2.uid
           WHERE T2.id IS NULL ) as step2
  on step1.uid = step2.uid

答案 1 :(得分:0)

您也可以使用此方法:

  select
    uid,nickname,sum(price) total
  from
  (
      select
      A.uid,
      A.nickname,
      (B.price) price
      from
      tableA A
      inner join TableB B
      on A.id = B.ida
      order by A.uid,A.id desc)cs
  group by cs.uid

SqlFiddle:http://sqlfiddle.com/#!9/f1d345/35

答案 2 :(得分:0)

您的查询中的问题是您只能使用完成分组的列,并使用select子句聚合函数。

所以正确的查询将是 -

SELECT A.uid,SUM(B.price) FROM A INNER JOIN B ON A.id = B.idA GROUP BY A.uid;

您无法使用这些打印名称,因为您正在uid上创建虚拟组,并且有两个名称为uid ='abcdef'。

答案 3 :(得分:-1)

http://www.example.com/page/5/