2

我有 2 个查询,并且想做一个像 sql 这样的连接

例如,我有这些表..

object Family extends Table[Long]("Family") {
  def id = column[Long]("id")
  def * = id
}

object Person extends Table[(Long, Long)]("Person") {
  def id = column[Long]("id")
  def FamilyId = column[Long]("FamilyId")
  def * = id ~ FamilyId ~ size
}
4

3 回答 3

4
val implicitInnerJoin = for {
  c <- Family
  s <- Person if c.id === s.FamilyId
} yield (c.id, s.id)
于 2013-09-02T11:21:17.600 回答
1

来自 Slick 文档:http ://slick.typesafe.com/doc/1.0.0/lifted-embedding.html#joining-and-zipping ,以下是 Slick 中的一些可能连接以及与之相关的一些粗略 SQL

val implicitCrossJoin = for {
  c <- Coffees
  s <- Suppliers
} yield (c.name, s.name)

//SELECT c.name, s.name FROM Coffees c, Suppliers s


val implicitInnerJoin = for {
  c <- Coffees
  s <- Suppliers if c.supID === s.id
} yield (c.name, s.name)
//SELECT c.name, s.name FROM Coffees c, Suppliers s where c.supID = s.id    

val explicitCrossJoin = for {
  (c, s) <- Coffees innerJoin Suppliers
} yield (c.name, s.name)
//SELECT c.name, s.name FROM Coffees c CROSS JOIN Suppliers s    

val explicitInnerJoin = for {
  (c, s) <- Coffees innerJoin Suppliers on (_.supID === _.id)
} yield (c.name, s.name)
//SELECT c.name, s.name FROM Coffees c INNER JOIN Suppliers s ON (c.supID = s.id)   

val explicitLeftOuterJoin = for {
  (c, s) <- Coffees leftJoin Suppliers on (_.supID === _.id)
} yield (c.name, s.name.?)
//SELECT c.name, s.name FROM Coffees c LEFT OUTER JOIN Suppliers s ON (c.supID = s.id)

val explicitRightOuterJoin = for {
  (c, s) <- Coffees rightJoin Suppliers on (_.supID === _.id)
} yield (c.name.?, s.name)
//SELECT c.name, s.name FROM Coffees c RIGHT OUTER JOIN Suppliers s ON (c.supID = s.id)

val explicitFullOuterJoin = for {
  (c, s) <- Coffees outerJoin Suppliers on (_.supID === _.id)
} yield (c.name.?, s.name.?)
//SELECT c.name, s.name FROM Coffees c FULL OUTER JOIN Suppliers s ON (c.supID = s.id)

如您所见,大多数构造都非常直接地映射到 SQL。

希望有帮助

于 2013-10-02T23:06:30.560 回答
0

这是 Slick 3.x 的更新答案:

val families = TableQuery[Family]
val people = TableQuery[Person]

val familyJoinQuery = for {
  family <- families
  person <- people if family.id === person.FamilyId
} yield (family, person)

或者,并且很少记录,您还可以执行以下操作:

val familyJoinQuery = families.join(people).on((family, person) => family.id === person.FamilyId)
于 2021-09-23T16:45:27.337 回答