内部加入MySQL表与表的总和

时间:2017-11-13 02:16:36

标签: mysql sql sum inner-join

我搜索了论坛并在表单上尝试了几个结果,但我仍在努力解决以下问题。 请你们给我以下建议:

Table 1: transactions
Rows: user_id, amount, received

Table 2: wallet
Rows: user_id, wallet_id

我需要加入2个结果:

结果1:

SELECT user_id, SUM(amount)FROM transactions WHERE received = '100' GROUP BY user_id

结果2:

SELECT * FROM transactions INNER JOIN wallet ON transactions.user_id = wallet.user_id

我要做的是通过使用user_id链接表2的wallet_id,并将其链接到表1中所有事务的user_id,其中= 100。我还需要在金额行上对结果求和。 因此它将显示每个user_id的总数并将钱包链接到它。

我试过了:

SELECT user_id, SUM(amount)FROM transactions
INNER JOIN wallet ON transactions.user_id = wallet.user_id
WHERE received = '100' GROUP BY user_id

但它不起作用。 请帮帮我们;-)

4 个答案:

答案 0 :(得分:2)

希望这有帮助。

SELECT user_id, wallet_id, SUM(amount)FROM transactions t
JOIN wallet w ON t.user_id = w.user_id
WHERE received = '100' GROUP BY user_id, wallet_id;

答案 1 :(得分:0)

只需按user_id,wallet_id

添加分组即可
SELECT user_id, wallet_id, SUM(amount)FROM transactions
INNER JOIN wallet ON transactions.user_id = wallet.user_id
WHERE received = '100' GROUP BY user_id, wallet_id

答案 2 :(得分:0)

如果您解释了代码失败的原因,那么修复起来会更容易。至少有一个错误是UINavigationController未定义。

一个简单的解决方案是使用 .centerblock { position: absolute; left: 50%; top: 50%; /* <<< here you can set the value you want */ transform: translate ( -50%, -50%) }

user_id

注意:如果USING是一个数字,则不要将SELECT user_id, SUM(t.amount) FROM transactions t INNER JOIN wallet w USING (user_id) WHERE t.received = '100' GROUP BY user_id; 括在单引号中。

或者,您可以通过限定列名来编写查询 - 并且您应该对所有列进行限定:

received

如果您还想要100,请将其加入SELECT w.user_id, SUM(t.amount) FROM transactions t INNER JOIN wallet w ON w.user_id = t.user_id WHERE t.received = '100' GROUP BY w.user_id; wallet_id

SELECT

答案 3 :(得分:0)

谢谢你们。你们好棒!!!!! 这对我有用:

SELECT wallet_id,received,SUM(amount)FROM transaction INNER JOIN wallet ON transaction.user_id = wallet.uid WHERE received =&#39; 100&#39; GROUP BY wallet_id