Groupby on multiple objects generates invalid SQL in slick

安稳与你 提交于 2019-12-25 16:25:26

问题


I am writing a query that calculates a possible score for a QuestionAnswer, when executing the query I get a PSQLException

Info about the model

A QuestionAnswer can have several (at least one) questionAnswerPossibilities, since there are multiple ways to answer the question correctly.

Every questionAnswerPossibility has several questionAnswerParts, in the query below we query the score per questionAnswerPossibility.

The Problematic Query

The query itself does generate SQL, but the SQL can not be executed

  def queryMogelijkePuntenByVragenViaOpenVragen()(implicit session: Session) = {
    (for{
      ovam <- OpenVraagAntwoordMogelijkheden //questionAnswerPossibilites
      ovad <- OpenVraagAntwoordOnderdelen if ovad.ovamId === ovam.id //questionAnswerParts
      ova <- OpenVraagAntwoorden if ovam.ovaId === ova.id //questionAnswers
    } yield ((ova, ovam), ovad.punten))
      .groupBy{ case ((ova, ovam), punten) => (ova, ovam)}
      .map{ case ((ova, ovam), query) => (ova, ovam, query.map(_._2).sum)}
}

Here the generated SQL (postgreSQL)

select x2."id", x2."vraag_id", x3."id", x3."volgorde", x3."ova_id", sum(x4."punten") 
from "open_vraag_antwoord_mogelijkheden" x3, "open_vraag_antwoord_onderdelen" x4, "open_vraag_antwoorden" x2 
where (x4."ovam_id" = x3."id") and (x3."ova_id" = x2."id")
group by (x2."id", x2."vraag_id"), (x3."id", x3."volgorde", x3."ova_id")

The problem is that the SQL can not execute , I get the following error

play.api.Application$$anon$1:
Execution exception[[
PSQLException: ERROR: column "x2.id" must appear in the GROUP BY clause or be used in an aggregate function
  Position: 8]]

The SQL that is genarated contains too many brackets, the last part of the SQL should be

group by x2."id", x2."vraag_id", x3."id", x3."volgorde", x3."ova_id"

However slick generates it with brackets, am I doing something wrong here? Or is this a bug?


回答1:


I solved the issue

...
    } yield ((ova.id, ovam.id), ovad.punten))

Because I now only yield the nessecary id's and not all data, the sql that is generated does not contain the unnecessary braces that caused the SQL error.

I really wanted more data than just those id's, but I can work around this by using this query as a subquery, the outer query will fetch all the needed data for me.



来源:https://stackoverflow.com/questions/18726742/groupby-on-multiple-objects-generates-invalid-sql-in-slick

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