我有桌子
表1
id text
1 A
1 B
2 C
表2
id text
1 x
1 f
2 y
2 z
我想以这种方式加入他们
1 A x
1 B f
2 C y
2 z
换句话说,我希望看到table1和table2中的所有文本按id分组,没有重复。 有什么想法吗?
更新:正如他们在评论中所说,逻辑不明确,我会尝试解释。 我在table_1中有当前值,在table_2中删除了值。 客户希望在一个表中按当前ID分组查看当前值和已删除的值。
答案 0 :(得分:1)
简单的解决方案,以获得接近您正在寻找的东西
SELECT t1.id, t1.text, t2.text
FROM tbl_1 t1
INNER JOIN tbl_2 t2
ON t1.id = t2.id
这将创建输出
1 A x
1 B x
2 C y
2 C z
现在唯一不同的是,重复文本x
和C
应该以某种方式删除。
<强>更新强> 前提条件:每个ID的重复项都在tbl_1或tbl_2中,而不是两者都有!
除上述简单解决方案外,加入分组选择将允许创建一种“CASE-Filters”以获得所需的输出。
SELECT
t1.id,
CASE
WHEN t2.text = txt_i2 THEN t1.text
END AS txt_t1,
CASE
WHEN t1.text = txt_i1 THEN t2.text
END AS txt_t2
FROM (
SELECT
i1.id,
i1.text AS txt_i1,
i2.text AS txt_i2
FROM tbl_1 i1
INNER JOIN tbl_2 i2
ON i1.id = i2.id
GROUP BY id
) i
INNER JOIN tbl_1 t1
ON i.id = t1.id
INNER JOIN tbl_2 t2
ON t1.id = t2.id
您应该创建tbl_1-tbl_2-join的视图以获得更具可读性的SQL:
CREATE OR REPLACE VIEW V_tbl_1_2 AS (
SELECT
t1.id,
t1.text AS txt_1,
t2.text AS txt_2
FROM tbl_1 t1
INNER JOIN tbl_2 t2
ON t1.id = t2.id
)
;
SELECT
t.id,
CASE
WHEN t.txt_2 = i.txt_2 THEN t.txt_1
END AS txt_t1,
CASE
WHEN t.txt_1 = i.txt_1 THEN t.txt_2
END AS txt_t2
FROM V_tbl_1_2 t
INNER JOIN (
SELECT *
FROM V_tbl_1_2
GROUP BY id
) i ON t.id = i.id
;
答案 1 :(得分:0)
答案 2 :(得分:0)
如果两个表中每个id
的项目不超过两个,并且两者都没有完全重复,则此方法有效。 (而且我还必须补充一点,这只有在MySQL能够吞下这个怪物并且不会被它窒息的情况下才有效。)
SELECT
COALESCE (t1.id, t2.id) AS id,
t1.text AS text1,
t2.text AS text2
FROM (
SELECT
t.id,
t.text,
CASE t.text WHEN m.text THEN 1 ELSE 2 END AS rowid
FROM table_1 t
INNER JOIN (
SELECT id, MIN(text) AS text
FROM table_1
GROUP BY id
) m ON t.id = m.id
) t1
FULL JOIN (
SELECT
t.id,
t.text,
CASE t.text WHEN m.text THEN 1 ELSE 2 END AS rowid
FROM table_2 t
INNER JOIN (
SELECT id, MIN(text) AS text
FROM table_2
GROUP BY id
) m ON t.id = m.id
) t2
ON t1.id = t2.id AND t1.rowid = t2.rowid
ORDER BY COALESCE (t1.id, t2.id), COALESCE (t1.rowid, t2.rowid)