【发布时间】:2018-04-25 17:09:31
【问题描述】:
我在使用 Hibernate 生成的 SQL 语句时遇到了一些问题。我想在给定的时间范围内或特定的日子让所有用户的生日。虽然特定日期的语句工作正常,但另一个只返回前 n 个用户,其中 n 是正确用户的数量。
考虑到这些数据:
ID name birthdate
1 firstUser 12.07.1990
2 user1 25.04.2007
3 user2 15.05.1992
4 user3 01.04.1988
首先生成特定日期的语句:
select
*
from
( select
distinct *
from
USERS user0_
where
calculateNextBirthday(user0_.birthDate) = TO_DATE('25.04.2018', 'dd.MM.yyyy')
order by
user0_.id asc )
where
rownum <= ?; // This will be the row count of this statement with the same where clause, i.e. 1 if there is only 1 matching user
正如我所说,此语句返回正确的用户(ID 为 2 的 user1)。
相同的语句,中间有:
select
*
from
( select
distinct *
from
USERS user0_
where
calculateNextBirthday(user0_.birthDate) between TO_DATE('01.04.2018', 'dd.MM.yyyy') and TO_DATE('30.04.2018', 'dd.MM.yyyy')
order by
user0_.id asc )
where
rownum <= ?; // This will be the row count of this statement with the same where clause, i.e. 1 if there is only 1 matching user
这个语句有一个奇怪的行为。如果我执行内部选择语句,结果将包含正确的用户 (user1)。但执行整个语句将返回第一个用户(firstUser,ID 为1)。像这样更改日期:
select
*
from
( select
distinct *
from
USERS user0_
where
calculateNextBirthday(user0_.birthDate) between TO_DATE('01.04.2018', 'dd.MM.yyyy') and TO_DATE('30.06.2018', 'dd.MM.yyyy')
order by
user0_.id asc )
where
rownum <= ?; // This will be the row count of this statement with the same where clause, i.e. 1 if there is only 1 matching user
将返回前两个用户(firstUser 和 user1),因为有两个匹配的用户(user1 和 user2)
如果我从 where 外部语句中删除 rownum,它只会返回正确的用户(下面的示例返回 user1)。
select
*
from
( select
distinct *
from
USERS user0_
where
calculateNextBirthday(user0_.birthDate) between TO_DATE('01.04.2018', 'dd.MM.yyyy') and TO_DATE('30.04.2018', 'dd.MM.yyyy')
order by
user0_.id asc )
所以我不知道 Oracle 从哪里获得第一个用户条目。
我在这里做错了什么还是 Oracle Oracle Database 10g Express Edition Release 10.2.0.1.0 中存在错误?
【问题讨论】:
-
rownum 不明确 - 它显然来自内部选择
-
@Randy 如何将 rownum 应用于内部选择?特别是因为它适用于 equal。
-
添加了更多细节。我希望它有助于理解我的问题。并且 rownumber 具有正确的编号。我不想要更多行,我想要正确的行。
-
您所做的似乎在我的 11.2.0.4 环境和 in an SQL Fiddle 中正常工作。还尝试了略有不同的数据which also works。您使用的是 Oracle 的哪个版本和补丁级别?您能否创建一个可重现的示例,最好是在另一个 SQL Fiddle 中?
-
好吧,我的错误比我想象的要老。现在是 10.2。我还尝试使用 SQL Fiddle 创建一个示例。