Sqlite3:显示多个外键的值

时间:2018-02-06 17:08:15

标签: sql sqlite foreign-keys

我有以下Sqlite数据库:

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;

如您所见,列main.fk_1main.fk_2引用id中的foreign_table字段。我想显示foreign_table.val而不是foreign_table.id的值。到目前为止,我已经提出了以下SQL语句:

-- 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
;

输出结果为:

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

这几乎是我想要的。我实际上想保留main表中的列名,因此输出应如下所示:

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

可以这样做吗?我加入观点的方法是否合理,还是有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:0)

经过一些进一步的研究后,我找到了一种方法来临时为创建的视图的列分配一个新名称。创建视图时,可以将自定义名称分配给视图中的列。我的解决方案现在看起来像这样:

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
;

这将产生所需的输出。