[英]How to get at the information from a SQLite table containing two foreign keys referencing the same column
As part of a personal project, I have built a database which contains a table of text files (with their path and basename as columns), and another table, which indicates which files are duplicates of other files. 作为个人项目的一部分,我建立了一个数据库,其中包含一个文本文件表(其路径和基本名称作为列),以及另一个表,该表指示哪些文件是其他文件的副本。
Here's how the first table looks : 这是第一个表的外观:
files(
filesid INTEGER PRIMARY KEY UNIQUE,
filename TEXT,
filesource TEXT,
path TEXT UNIQUE)
And here's the second one : 这是第二个:
duplicatefiles(
id INTEGER PRIMARY KEY UNIQUE,
filesid INTEGER,
duplicateof INTEGER,
songid INTEGER,
FOREIGN KEY(filesid) REFERENCES lyricsfiles(filesid),
FOREIGN KEY(duplicateof) REFERENCES lyricsfiles(filesid),
This last table has two columns of foreign keys referencing ids in the files table, indicating that the two files are duplicate from each other. 最后一个表具有两列外键,这些外键引用了文件表中的ID,指示这两个文件彼此重复。
I did this to minimize information duplication but I now realise that I have no idea how to query this table to get what I actually want, which is the path to both files. 我这样做是为了最大程度地减少信息重复,但是现在我意识到我不知道如何查询该表以获取我真正想要的东西,这是两个文件的路径。 I have read about aliases, but I have been unable to find documentation on how to use them in this case.
我已经阅读了有关别名的信息,但是在这种情况下,我找不到有关如何使用别名的文档。
I'm using sqlite3 and python3. 我正在使用sqlite3和python3。
So my questions are : what's the correct way to query the database as it is to get at the information I need ? 所以我的问题是:查询数据库以获取所需信息的正确方法是什么? And what would be a better way to represent this information in a database ?
在数据库中表示此信息的更好方法是什么?
you need to join your table files
2 times. 您需要将表
files
加入2次。 To do so you need table aliases: 为此,您需要表别名:
SELECT
ORI.filesid original_filesid
,ORI.filename original_filename
,ORI.filesource original_filesource
,DUP.filesid duplicate_filesid
,DUP.filename duplicate_filename
,DUP.filesource duplicate_filesource
FROM duplicatefiles DPF
JOIN files ORI
ON ORI.filesid = DPF.duplicateof
JOIN files DUP
ON DUP.filesid = DPF.filesid
you see that i joined files
as the alias ORI indicating that this alias represents the original file (also see the join condition ORI.filesid = DPF.duplicateof
). 您会看到我以别名ORI的形式加入
files
,这表明该别名表示原始文件(另请参见加入条件ORI.filesid = DPF.duplicateof
)。 The duplicates are joined via the tables alias DUP. 通过表别名DUP连接重复项。 Using the alias you then select the field you want and you could also rename them for better understanding
ORI.filesid
is renamed to original_filesid
. 然后使用别名选择所需的字段,还可以重命名它们以更好地理解
ORI.filesid
重命名为original_filesid
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.