gpt4 book ai didi

android - Sqlite限制具有相同ID的重复行

转载 作者:行者123 更新时间:2023-12-04 07:23:44 27 4
gpt4 key购买 nike

我正在使用 android SQLite 数据库,结果如下:

 id | root_id | parent_id   |name
----------------------------------
613 | null | null | m1
612 | null | null | m4
570 | null | null | m1
635 | 570 | 570 | m6
653 | 570 | 635 | m1
652 | 570 | 635 | m3
632 | 570 | 570 | m9
392 | null | null | m2
753 | 392 | 392 | m5
751 | 392 | 392 | m4
391 | null | null | m7
我通过下面的查询得到了这个结果:
WITH RECURSIVE all_employees(id, root_id, parent_id, name) AS (
SELECT id, id AS root_id, parent_id, name FROM employees WHERE parent_id IS NULL
UNION ALL
SELECT c.id, (CASE WHEN c.parent_id IS NOT NULL THEN p.root_id END), c.parent_id, c.name FROM employees c JOIN all_employees p ON p.id = c.parent_id ORDER BY id DESC
)

SELECT id, (CASE WHEN id != root_id THEN root_id ELSE NULL END) root_id, parent_id, name FROM all_employees
我想为具有相同 root_id 的重复行设置限制,例如:
加载 2 行 root_id 570 和 1 行 root_id 392:
 id | root_id | parent_id   |name
----------------------------------
613 | null | null | m1
612 | null | null | m4
570 | null | null | m1
635 | 570 | 570 | m6
653 | 570 | 635 | m1
392 | null | null | m2
753 | 392 | 392 | m5
391 | null | null | m7

最佳答案

创建另一个 CTE :

counters(root_id, n) AS (VALUES (570, 2), (392, 1)) 
您返回所有 root_id 的地方s 你想限制他们的行和每一行的行数,然后使用 LEFT递归的加入 CTE到那个。
最后,在 WHERE中设置条件带有相关子查询的子句:
WITH 
RECURSIVE all_employees(id, root_id, parent_id, name) AS (
SELECT id, id AS root_id, parent_id, name
FROM employees
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, (CASE WHEN c.parent_id IS NOT NULL THEN p.root_id END), c.parent_id, c.name
FROM employees c JOIN all_employees p
ON p.id = c.parent_id
),
counters(root_id, n) AS (VALUES (570, 2), (392, 1))
SELECT a.id, (CASE WHEN a.id <> a.root_id THEN a.root_id END) root_id, a.parent_id, a.name
FROM all_employees a LEFT JOIN counters c
ON c.root_id = a.root_id
WHERE c.root_id IS NULL
OR (SELECT COUNT(*) FROM all_employees b WHERE b.root_id IS a.root_id AND b.id <= a.id) <= c.n
请注意 ORDER BY CTE内的条款没用,因为当您从 CTE 中选择时,不能保证行会按该顺序返回。 .
您可以在最终查询中设置所需行的顺序。

关于android - Sqlite限制具有相同ID的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68343060/

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