递归sql子集查询,使用connect by

发布于 2024-09-11 10:21:20 字数 334 浏览 10 评论 0原文

我有两个看起来有点像这样的表

AGR_TERR_DEF_TERRS
  ID
  DEF_ID
  TERRITORY_ID (foreign key links to TERRITORIES.ID)

TERRITORIES
  ID
  NAME
  PARENT_ID
(parent_id and id are recursive)

给定两个 DEF_ID,我需要一个函数来检查一个表的领土是否是另一个的完整子集。 我一直在玩 CONNECT BY 和 INTERSECT,但写得一团糟,而不是一个有用的函数。

我希望有一个(相对)简单的 SQL 查询可以工作。

I have two tables that look a little like this

AGR_TERR_DEF_TERRS
  ID
  DEF_ID
  TERRITORY_ID (foreign key links to TERRITORIES.ID)

TERRITORIES
  ID
  NAME
  PARENT_ID
(parent_id and id are recursive)

Given two DEF_IDs, I need a function which checks whether the territories of one is a complete subset of the other.
I've been playing with CONNECT BY, and INTERSECT, but have written a big mess rather than a useful function.

I'm hoping there will be a (relatively) easy SQL query that works.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蘸点软妹酱 2024-09-18 10:21:20

基于 @Tony Andrews 的回答,当 def_id_1 隐含的领土是 def_id_2 的子集时,这将产生零行,

select id from territories start with id in
  (select territory_id from agr_terr_def_terrs where def_id = :def_id_1)
  connect by parent_id = prior id
minus
select id from territories start with id in
  (select territory_id from agr_terr_def_terrs where def_id = :def_id_2)
  connect by parent_id = prior id

Building on @Tony Andrews answer this would produce zero rows when the territories implied by def_id_1 are a subset of those for def_id_2,

select id from territories start with id in
  (select territory_id from agr_terr_def_terrs where def_id = :def_id_1)
  connect by parent_id = prior id
minus
select id from territories start with id in
  (select territory_id from agr_terr_def_terrs where def_id = :def_id_2)
  connect by parent_id = prior id
将军与妓 2024-09-18 10:21:20

给定获取给定 DEF_ID 的所有恐怖的查询(我不太确定您的表是什么),如果以下查询不返回任何行,则 DEF_ID A 是 DEF_ID B 的子集:

select statement for A
MINUS
select statement for B

这有帮助吗?

Given the query to get all the terrories for a given DEF_ID (I'm not quite sure what that is with your tables), DEF_ID A is a subset of DEF_ID B if the following query returns no rows:

select statement for A
MINUS
select statement for B

Does that help?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文