连接和合并两个不同行具有相同 ID 的表

Joining and combining two tables that have the same ID for different rows

在 SQLite 中我有两个 table,tab_atab_b。两者都有一些相似的列和一些不同的列:

tab_a -> id | utc | name | data_1 | data_2 | data_3
tab_b -> id | utc | name | data_x | data_y | data_x

所以在这个例子中,两个 table 都有列 idutcname 和其他三个专用于 table 的列]s。此外,两个 table 中的 id 字段可以包含相同的值。但是,它们不是同一个数据集!因此,例如 tab_a 中的 id = 1 是另一个数据集,而不是 tab_b 中的 id = 1 - 它们只是随机具有相同的 ID。

现在我想(在外部?)连接这两个 table 以获得它们的所有记录的组合列表,当然只有共享列。但是由于两个 table 的 ID 可以相同,我需要在我的联接中添加一个列来说明 table 这一行来自什么。

因此,例如合并后的结果可能如下所示:

id | tab   | utc  | name
---+-------+------+-----
 1 | tab_a | ...  | ...
 2 | tab_a | ...  | ...
 2 | tab_b | ...  | ...
 3 | tab_b | ...  | ...
 4 | tab_a | ...  | ...
 4 | tab_b | ...  | ...

如何以这种方式在 SQLite 中加入两个 table 并添加这个“自定义”列?如果那不可能,我应该在我的案例中使用什么其他“最佳实践”方法?

您必须使用 UNION,而不是 JOIN 来达到您的目的:

CREATE TABLE tab_a (
    id int PRIMARY KEY,
    utc text,
    name text
);
CREATE TABLE tab_b (
    id int PRIMARY KEY,
    utc text,
    name text
);

INSERT INTO tab_a (id, utc, name)
VALUES (1, "utc1", "name1"), (2, "utc2", "name2");

INSERT INTO tab_b (id, utc, name)
VALUES (1, "utc3", "name3"), (2, "utc4", "name4");

SELECT id, name, utc, "tab_a" as tab from tab_a
UNION SELECT id, name, utc, "tab_b" as tab from tab_b;

回复:

id name utc tab
1 name1 utc1 tab_a
1 name3 utc3 tab_b
2 name2 utc2 tab_a
2 name4 utc4 tab_b

Example in DB Fiddle