Calculate table column using over table on server side

余生颓废 提交于 2019-12-07 05:35:28
Erwin Brandstetter

The basic query could be:

SELECT r.*, COALESCE(n.ct, 0) AS ct
FROM   registry r
LEFT   JOIN (
   SELECT registry_id, count(*) AS ct
   FROM   rows
   GROUP  BY registry_id
   ) n USING (registry_id);

The LEFT [OUTER] JOIN is essential so you do not filter rows from registry without related rows in rows.

COALESCE to return 0 instead of NULL where no related rows are found.

There are many related answers on SO. One here:

You could wrap this in a VIEW for convenience:

CREATE VIEW reg_rn AS
SELECT ...

... which you query like a table.

Aside: It's unwise to use reserved SQL key words as identifiers. row is a no-go for a column name (even if allowed in Postgres).

sheh

Thanks Erwin Brandstetter for awesome answer, using it, I wrote code for my scala-slick application.

Scala code looks much more complicated than plain sql:

val registryQuery = registries.filter(_.userId === userId)
val rowQuery = rows groupBy(_.registryId) map { case (regId, rowItems) => (regId, rowItems.length)}
val q = registryQuery joinLeft rowQuery on (_.registryId === _._1) map {
  case (registry, rowsCnt) => (registry, rowsCnt.map(_._2))
}

but it works!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!