gpt4 book ai didi

sqlite - 选择特定值 SQLite

转载 作者:行者123 更新时间:2023-12-01 16:24:58 24 4
gpt4 key购买 nike

我有一个问题,我正在使用 sqlite,

首先我创建了一个表:

 CREATE TABLE tree(
id_tree integer PRIMARY KEY AUTOINCREMENT,
id_boss TEXT,
id_child TEXT,
answ TEXT);

插入一些值:

 INSERT INTO tree(id_boss,id_child,answ) VALUES('1','8','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('1',null,'F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('8','P1','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('8','2','F');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','P2','T');
INSERT INTO tree(id_boss,id_child,answ) VALUES('2','P3','F');

并执行查询:

 WITH RECURSIVE
ancestor(id) AS (
VALUES('P3')
UNION ALL
SELECT tree.id_boss
FROM tree JOIN ancestor ON tree.id_child = ancestor.id
)
SELECT id FROM ancestor;

结果是:

  P3
2
8
1

我的问题是,如何进行查询以选择“T”值中的 id_boss 并忽略“F”中的所有值?

结果应该是这样的:

  P3
1

最佳答案

您无法从 CTE 内部过滤掉 F 记录,因为这会破坏树中的连接。相反,您必须返回 answ 值,并在第二步中将它们用作过滤器:

WITH RECURSIVE
ancestors(id, answ) AS (
VALUES('P3', 'T')
UNION ALL
SELECT tree.id_boss, tree.answ
FROM tree JOIN ancestors ON tree.id_child = ancestors.id
)
SELECT id FROM ancestors WHERE answ = 'T';

关于sqlite - 选择特定值 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23710861/

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