来自第二个表(TOP10)的MySQL INNER JOIN

时间:2014-12-16 00:35:48

标签: mysql sql select group-by sum

$stmt = $conn->prepare('SELECT  a.*, c.*, SUM(a.money+b.RESULT) AS ARESULT
FROM users a 
    INNER JOIN bankaccounts c
        ON a.id = c.owner
    INNER JOIN
    (
        SELECT owner, SUM(amount) AS RESULT
        FROM bankaccounts
        GROUP BY owner
    ) b ON a.id = b.owner
    ORDER BY ARESULT DESC LIMIT 10');

问题是什么,只显示错误一条记录?我想列出最多10条记录 - 比如前十名最富有的人[钱+(所有他的银行账户金额)]

让我们说..我有2张桌子。

表:用户

ID | username | money

1  | richman | 500

2  | richman2 | 600

表:bankaccounts

ID | owner | amount

65 | 1     | 50

68 | 1     | 50

29 | 2     | 400

所以它会列出:

  1. richman2 1000 $

  2. richman 600 $

2 个答案:

答案 0 :(得分:1)

尝试使用子查询...

$stmt = $conn->prepare('SELECT  a.*, 
    IFNULL((SELECT SUM(amount) FROM bankaccounts b WHERE b.owner=a.id),0) AS BANK_MONEY,
    (IFNULL(a.money,0) + IFNULL((SELECT SUM(amount) FROM bankaccounts c WHERE c.owner=a.id),0)) AS ARESULT
    FROM users a 
    ORDER BY ARESULT DESC LIMIT 0, 10');

编辑:为银行帐户总计添加了一个字段

EDIT2:如果用户不在BankAccounts表中,则将IFNULL添加到SQL语句

答案 1 :(得分:0)

试试这个:

SELECT  a.*, (a.money + b.RESULT) AS ARESULT
FROM users a 
INNER JOIN (SELECT owner, SUM(amount) AS RESULT
            FROM bankaccounts
            GROUP BY owner
          ) b ON a.id = b.owner
ORDER BY ARESULT DESC 
LIMIT 10