我想创建一个返回所有具有用户数的组(包括空组)的查询
SELECT g.id, count(relation.user_id) FROM groups g
FULL JOIN users2groups relation ON g.id=r.group_id
GROUP BY g.id;
此模型:
class Users(tag: Tag) extends Table[User](tag, "users") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
...
}
class Groups(tag: Tag) extends Table[Group](tag, "groups") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
...
}
val users = TableQuery[Users]
val groups = TableQuery[Groups]
/** relation for users and group */
class Users2Groups(tag: Tag) extends Table[(Long,Long)](tag, "users2groups") {
def userId = column[Long]("user_id")
def groupId = column[Long]("group_id")
def user = foreignKey("user_fk", userId, users)(_.id)
def group = foreignKey("group_fk", groupId, groups)(_.id)
def * = (userId, groupId)
def ? = (userId.?, groupId.?)
def pk = primaryKey("pk_user2group", (userId, userId))
}
这是我的光滑解决方案:
val query = for {
(g, rel) <-
groups leftJoin
users2groups on (_.id === _.groupId)
} yield (g, rel.groupId.?)
val result = query.groupBy(_._1.id).map(e => (e._1, e._2.length)).list
result foreach println
但它无法正常工作。它为空组返回不正确的用户数量(返回用户数= 1而不是0)。
我的环境:scala-2.11.2,slick-2.1.0,PostgreSQL