使用SLICK的递归树型表查询 [英] Recursive tree-like table query with Slick
本文介绍了使用SLICK的递归树型表查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的表数据形成一个树结构,其中一行可以引用同一个表中的父行。
我试图使用SLICK实现的是编写一个返回一行及其所有子行的查询。另外,我也想做同样的事情,但编写一个将返回子对象及其所有祖先的查询。
换言之:
findDown(1)
应返回
List(Group(1, 0, "1"), Group(3, 1, "3 (Child of 1)"))
findUp(5)
应返回
List(Group(5, 2, "5 (Child of 2)"), Group(2, 0, "2"))
这是一个功能齐全的工作表(除了缺少的解决方案;-)。
package com.exp.worksheets
import scala.slick.driver.H2Driver.simple._
object ParentChildTreeLookup {
implicit val session = Database.forURL("jdbc:h2:mem:test1;", driver = "org.h2.Driver").createSession()
session.withTransaction {
Groups.ddl.create
}
Groups.insertAll(
Group(1, 0, "1"),
Group(2, 0, "2"),
Group(3, 1, "3 (Child of 1)"),
Group(4, 3, "4 (Child of 3)"),
Group(5, 2, "5 (Child of 2)"),
Group(6, 2, "6 (Child of 2)"))
case class Group(
id: Long = -1,
id_parent: Long = -1,
label: String = "")
object Groups extends Table[Group]("GROUPS") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def id_parent = column[Long]("ID_PARENT")
def label = column[String]("LABEL")
def * = id ~ id_parent ~ label <> (Group, Group.unapply _)
def autoInc = id_parent ~ label returning id into {
case ((_, _), id) => id
}
def findDown(groupId: Long)(implicit session: Session) = { ??? }
def findUp(groupId: Long)(implicit session: Session) = { ??? }
}
}
在findDown
中非常糟糕的静态尝试可能如下所示:
private def groupsById = for {
group_id <- Parameters[Long]
g <- Groups; if g.id === group_id
} yield g
private def childrenByParentId = for {
parent_id <- Parameters[Long]
g <- Groups; if g.id_parent === parent_id
} yield g
def findDown(groupId: Long)(implicit session: Session) = { groupsById(groupId).list union childrenByParentId(groupId).list }
但是,我正在寻找一种让SLICK使用id和id_parent链接递归搜索同一个表的方法。任何其他解决问题的好方法都是受欢迎的。但请记住,最好将数据库往返次数降至最低。
推荐答案
您可以尝试从slick调用。向上执行层次结构的SQL调用如下所示(这是针对SQL Server的):
WITH org_name AS
(
SELECT DISTINCT
parent.id AS parent_id,
parentname.label as parent_label,
child.id AS child_id,
childname.ConceptName as child_label
FROM
Group parent RIGHT OUTER JOIN
Group child ON child.parent_id = parent.id
),
jn AS
(
SELECT
parent_id,
parent_label,
child_id,
child_label
FROM
org_name
WHERE
parent_id = 5
UNION ALL
SELECT
C.parent_id,
C.parent_label,
C.child_id,
C.child_label
FROM
jn AS p JOIN
org_name AS C ON C.child_id = p.parent_id
)
SELECT DISTINCT
jn.parent_id,
jn.parent_label,
jn.child_id,
jn.child_label
FROM
jn
ORDER BY
1;
如果要在层次结构中向下移动,请更改行:
org_name AS C ON C.child_id = p.parent_id
至
org_name AS C ON C.parent_id = p.child_id
这篇关于使用SLICK的递归树型表查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文