在 SQL 中进行联接时如何不排除项目?

问题描述 投票:0回答:1

我对 SQL 比较陌生,并尝试使用联接从多个表中检索信息,但某些项目被排除在查询之外。

以下是表格:

账户:

account_id | account_holder | balance
-------------------------------------
1          | John Doe       | 1000.00
2          | Jane Smith     | 500.00
3          | Alice Johnson  | 2000.00

交易

transaction_id | account_id | amount | transaction_date
--------------------------------------------------------
1              | 1          | -500.00| 2024-04-01
2              | 1          | -200.00| 2024-04-05
3              | 2          | -100.00| 2024-04-02

我的询问:

SELECT a.account_id, a.account_holder, SUM(t.amount) AS total_transactions
FROM accounts a
JOIN transactions t ON a.account_id = t.account_id
GROUP BY a.account_id, a.account_holder;

然而,这就是我的结果

account_id | account_holder | total_transactions
-----------------------------------------------
1          | John Doe       | -700.00
2          | Jane Smith     | -100.00

结果集中缺少“Alice Johnson”,因为它还没有任何交易。我怎样才能包含所有帐户,即使它们没有任何交易?

对此的任何帮助或指导将不胜感激。谢谢!

sql oracle
1个回答
1
投票

这里您需要的是外连接,特别是左外连接,它将包括账户表中的所有行,无论交易表中是否有匹配的行。

您可以修改查询以使用左外连接,如下所示:

LEFT JOIN transactions t ON a.account_id = t.account_id
© www.soinside.com 2019 - 2024. All rights reserved.