gpt4 book ai didi

android - CREATE VIEW of UNION 两个表,合并行

转载 作者:行者123 更新时间:2023-11-30 01:59:42 25 4
gpt4 key购买 nike

我有两个几乎相同的表,分别代表来自服务器的数据和用户输入的数据。我想向用户显示来自两者的组合数据的列表,合并一个文本列值的任何重复项。选择一行后,我需要能够访问子表中的数据,因此需要主键以及该键来自哪个表。

两个表对 (fk_id, column_a) 都有唯一约束。

服务器表:

_id | fk_id | column_a
----------------------
1 | 1 | val 1
2 | 1 | val 2
3 | 2 | val 3

用户输入的表:

_id | uuid | fk_id | column_a
-----------------------------
1 | xxxx | 1 | val 1
2 | xxxx | 1 | val 4
3 | xxxx | 2 | val 5

我需要的搜索结果是:

_id | server_id | user_id | fk_id | column_a
--------------------------------------------
1 | 1 | 1 | 1 | val 1
2 | 2 | | 1 | val 2
3 | 3 | | 2 | val 3
2 | | 2 | 1 | val 4
3 | | 3 | 2 | val 5

我实际上并不关心结果集的 _id 列中的内容,但我需要 _id,因为我在 Android 中使用 CursorAdaptor。

我希望使用这样的 View 来做到这一点:

CREATE VIEW all_values AS
SELECT
_id, _id AS server_id, 0 AS user_id, fk_id, column_a
FROM
server_table
UNION SELECT
_id, 0 AS server_id, _id AS user_id, fk_id, column_a
FROM
user_table
ORDER BY column_a;

我可以这样查询:

SELECT * FROM all_values WHERE fk_id = ?

这可以使用 UNION 来实现吗? UNION 将不包含重复值,而 UNION ALL 将包含所有值。有没有办法合并重复项,或者我是否需要根据 column_a 的值进行联接?

最佳答案

UNION 将删除重复项,但仅在一个子查询中包含 NULL 值的行不是重复项。

你必须以艰难的方式做到这一点:

首先,此查询获取所有未更改的行:

(SELECT _id, fk_id, column_a FROM server_table
INTERSECT
SELECT _id, fk_id, column_a FROM user_table)

可以直接输出这些行:

SELECT _id, _id AS server_id, _id AS user_id, fk_id, column_a
FROM (SELECT _id, fk_id, column_a FROM server_table
INTERSECT
SELECT _id, fk_id, column_a FROM user_table);

仅服务器行是服务器表中不在子查询中的那些行:

SELECT _id, _id AS server_id, NULL AS user_id, fk_id, column_a
FROM server_table
WHERE _id NOT IN (SELECT _id FROM (SELECT _id, fk_id, column_a FROM server_table
INTERSECT
SELECT _id, fk_id, column_a FROM user_table));

仅限用户的行是用户表中不在子查询中的那些行:

SELECT _id, NULL AS server_id, _id AS user_id, fk_id, column_a
FROM user_table
WHERE _id NOT IN (SELECT _id FROM (SELECT _id, fk_id, column_a FROM server_table
INTERSECT
SELECT _id, fk_id, column_a FROM user_table));

然后将这三个结合起来:

SELECT _id, _id AS server_id, _id AS user_id, fk_id, column_a
FROM (SELECT _id, fk_id, column_a FROM server_table
INTERSECT
SELECT _id, fk_id, column_a FROM user_table)
UNION ALL
SELECT _id, _id, NULL, fk_id, column_a
FROM server_table
WHERE _id NOT IN (SELECT _id FROM (SELECT _id, fk_id, column_a FROM server_table
INTERSECT
SELECT _id, fk_id, column_a FROM user_table))
UNION ALL
SELECT _id + 100000000, NULL, _id, fk_id, column_a
FROM user_table
WHERE _id NOT IN (SELECT _id FROM (SELECT _id, fk_id, column_a FROM server_table
INTERSECT
SELECT _id, fk_id, column_a FROM user_table));

(需要 + 100000000 或类似的东西才能获得在整个结果中唯一的 _id 值。)

关于android - CREATE VIEW of UNION 两个表,合并行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31670016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com