简体   繁体   中英

Sqlite3: display value of multiple foreign keys

I have the following Sqlite database:

BEGIN TRANSACTION;
CREATE TABLE "main" (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `fk_1`  INTEGER NOT NULL,
    `fk_2`  INTEGER NOT NULL,
    FOREIGN KEY(`fk_1`) REFERENCES `foreign_table`(`id`) ON DELETE SET NULL,
    FOREIGN KEY(`fk_2`) REFERENCES `foreign_table`(`id`) ON DELETE SET NULL
);
INSERT INTO `main` VALUES (1,1,2);
INSERT INTO `main` VALUES (2,2,3);
INSERT INTO `main` VALUES (3,1,4);
INSERT INTO `main` VALUES (4,2,4);
INSERT INTO `main` VALUES (5,2,3);
CREATE TABLE "foreign_table" (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `val`   TEXT NOT NULL UNIQUE
);
INSERT INTO `foreign_table` VALUES (1,'val1');
INSERT INTO `foreign_table` VALUES (2,'val2');
INSERT INTO `foreign_table` VALUES (3,'val3');
INSERT INTO `foreign_table` VALUES (4,'val4');
CREATE VIEW bfk as select * from foreign_table;
CREATE VIEW afk as select * from foreign_table;
COMMIT;

As you can see, columns main.fk_1 and main.fk_2 reference the id field in foreign_table . I would like to display the value of foreign_table.val instead of foreign_table.id . So far I have come up with the following SQL statetment:

-- uncomment if views have to be created first
-- create temporary view afk as select * from foreign_table;
-- create temporary view bfk as select * from foreign_table;
select main.id, afk.val, bfk.val from main
left outer join afk on main.fk_1=afk.id
left outer join bfk on main.fk_2=bfk.id
;

The output is:

id | val  | val
---+------+------
1  | val1 | val2
2  | val2 | val3
3  | val1 | val4
4  | val2 | val4
5  | val2 | val3

This is almost what I want. I would actually like to keep the column names from main table, so the output should look like this:

id | fk_1 | fk_2
---+------+------
1  | val1 | val2
2  | val2 | val3
3  | val1 | val4
4  | val2 | val4
5  | val2 | val3

Can this be done? Is my approach with joining the views reasonable or is there a better way to do this?

After some further research I found a way to temporarily assign a new name to the columns of the created views. When creating the views one can assign custom names to the columns in the view. My solution now looks like this:

create temporary view if not exists afk (id,fk_1) as select id, val from foreign_table;
create temporary view if not exists bfk (id,fk_2) as select * from foreign_table;
select main.id, afk.fk_1, bfk.fk_2 from main
left outer join afk on main.fk_1=afk.id
left outer join bfk on main.fk_2=bfk.id
;

This will produce the desired output.

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