我正在尝试使用PostgreSQL作为Hibernate / JPA的数据库。但是,执行简单查询时出错。我的查询如下:
SELECT DISTINCT p FROM UserProfile p ORDER BY :order
当我执行查询时,我将为:order传递类似“lastLoginDate”的值。但是,在尝试执行查询时出现以下异常:
ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
Position: 781
使用MySQL作为数据库,这个查询工作正常,但我们想转向PostgreSQL。我的整体配置和数据库连接是正确的,因为我看到正确创建的表。有什么我想念的吗?我需要设置配置属性吗?您可以给予的任何帮助将非常感谢。谢谢!
答案 0 :(得分:7)
Postgresql禁止查询,因为它是ambiguous:
there's actually a definitional reason for it. Consider SELECT DISTINCT x FROM tab ORDER BY y; For any particular x-value in the table there might be many different y values. Which one will you use to sort that x-value in the output?
目前还不是很清楚你想要什么(一个例子?),但如果你打算按':order'列排序所有记录,然后删除重复的值,你可以先用DISTINCT ON :,然后重新排序:
SELECT p FROM
( SELECT DISTINCT ON (p) * from UserProfile ORDER BY p , :order)
AS UserProfileUniq
ORDER BY :order ;