SQLite 3 - 将 4 个表连接在一起而不重复记录
SQLite 3 - Joining 4 tables together without re-repeating records
我对SQL的查询语言比较陌生,我需要提醒一下我做错了什么。我事先意识到我的数据库结构不是最佳的,因此非常感谢您在阅读我的问题时可能想到的任何提示。
这是我正在尝试做的事情:
我有四个不同的table,四个都包含了以前交易的记录信息。 table 具有三个相关列,数量、日期和用户 ID。我想从所有四列中提取 select 金额和日期,以便输出为四行,每行包含 table 之一的金额和日期。方法如下(日期保存为长值):
Table 1
Row Amount Date UserID
1 1000 0 1
2 2000 2674800000 1
3 3000 5094000000 1
Table 2
Row Amount Date UserID
1 1000 0 1
2 2000 2674800000 1
3 3000 5094000000 1
我想要的输出
Row Amount Date UserID
1 1000 0 1
2 1000 0 1
3 2000 2674800000 1
4 2000 2674800000 1
5 3000 5094000000 1
6 3000 5094000000 1
以上是我希望我的数据在新视图中的外观,但我得到的是每个数量三个条目(因此,三个条目分别为 1000、2000 和 3000)...如果我添加另一个 table混进去,好像呈指数增长。
这是我当前的 SQL 查询:
SELECT T.Amount, T.Date FROM (SELECT Amount, Date, UserID FROM LoanRecords) AS T JOIN (SELECT Amount, Date, UserID FROM ExpenseRecords) AS E ON T.UserID = E.UserID
另外,如果有人能给我一些关于如何让它也显示每个日期的 SUM() 总数的指示,那就太好了。
你会使用 union all
:
SELECT T.Amount, T.Date, T.UserID
FROM ((SELECT Amount, Date, UserID FROM LoanRecords
) UNION ALL
(SELECT Amount, Date, UserID FROM ExpenseRecords
)
) t;
实际上,不需要子查询:
SELECT Amount, Date, UserID FROM LoanRecords
UNION ALL
SELECT Amount, Date, UserID FROM ExpenseRecords
ORDER BY UserID, Date;
我添加了 ORDER BY
因为这似乎是查询意图的一部分。
您可以在任一查询中使用 UNION ALL
添加其他表。
我对SQL的查询语言比较陌生,我需要提醒一下我做错了什么。我事先意识到我的数据库结构不是最佳的,因此非常感谢您在阅读我的问题时可能想到的任何提示。
这是我正在尝试做的事情:
我有四个不同的table,四个都包含了以前交易的记录信息。 table 具有三个相关列,数量、日期和用户 ID。我想从所有四列中提取 select 金额和日期,以便输出为四行,每行包含 table 之一的金额和日期。方法如下(日期保存为长值):
Table 1
Row Amount Date UserID
1 1000 0 1
2 2000 2674800000 1
3 3000 5094000000 1
Table 2
Row Amount Date UserID
1 1000 0 1
2 2000 2674800000 1
3 3000 5094000000 1
我想要的输出
Row Amount Date UserID
1 1000 0 1
2 1000 0 1
3 2000 2674800000 1
4 2000 2674800000 1
5 3000 5094000000 1
6 3000 5094000000 1
以上是我希望我的数据在新视图中的外观,但我得到的是每个数量三个条目(因此,三个条目分别为 1000、2000 和 3000)...如果我添加另一个 table混进去,好像呈指数增长。
这是我当前的 SQL 查询:
SELECT T.Amount, T.Date FROM (SELECT Amount, Date, UserID FROM LoanRecords) AS T JOIN (SELECT Amount, Date, UserID FROM ExpenseRecords) AS E ON T.UserID = E.UserID
另外,如果有人能给我一些关于如何让它也显示每个日期的 SUM() 总数的指示,那就太好了。
你会使用 union all
:
SELECT T.Amount, T.Date, T.UserID
FROM ((SELECT Amount, Date, UserID FROM LoanRecords
) UNION ALL
(SELECT Amount, Date, UserID FROM ExpenseRecords
)
) t;
实际上,不需要子查询:
SELECT Amount, Date, UserID FROM LoanRecords
UNION ALL
SELECT Amount, Date, UserID FROM ExpenseRecords
ORDER BY UserID, Date;
我添加了 ORDER BY
因为这似乎是查询意图的一部分。
您可以在任一查询中使用 UNION ALL
添加其他表。