简体   繁体   中英

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.

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.

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. 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 ). The duplicates are joined via the tables alias 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM