简体   繁体   English

DBMS_RANDOM似乎不起作用

[英]DBMS_RANDOM doesn't seem to work

I am still fairly new to Oracle SQL here, but I have scoured the internet to be able to just randomly pull a row from a table and saw a code like this. 我在这里对Oracle SQL还是很陌生,但是我已经搜寻了Internet以便能够从表中随机抽取一行并看到这样的代码。

firstNameGen = connection.prepareStatement(
    "SELECT firstName "
        +"FROM (SELECT firstName "
        +"FROM firstNames "
        +"ORDER BY dbms_random.value) "
    +"WHERE ROWNUM = 1");

It is not working for me. 它对我不起作用。 Obviously, I did change all the column and table names to match my own database, but it just tells me "ERROR 42X01: Syntax error: Encountered "WHERE" at line 1, column 58." 显然,我确实更改了所有列名和表名以匹配我自己的数据库,但这只是告诉我“错误42X01:语法错误:在第1行第58列遇到了“ WHERE”。

I'm working in Eclipse. 我正在Eclipse中工作。 Do I need to import the functionality to use dbms_random or am I just missing something? 我是否需要导入功能以使用dbms_random还是缺少一些东西? Any help would be appreciated. 任何帮助,将不胜感激。

i'm not sure but order by dbms_random.value may not working properly when using extra layers for example jdbc. 我不确定,但是在使用额外的层(例如jdbc)时,按dbms_random.value排序may无法正常工作。 also when you order by <expression returning a number> , it orders by the expression , not a "column" however you want only one value to display, I can say two alternate ways: 同样,当您通过<expression returning a number>排序时, it orders by the expression排序,而不是“列”进行排序,但是您只希望显示一个值,我可以说两种选择:

  1. Just add the dbms_random.value as a column to the query and order by that. 只需将dbms_random.value作为列添加到查询中,并以此排序即可。

     select * from (select firstName , dbms_random.value as ran from firstNames order by ran) where rownum=1; 
  2. use sample() 使用sample()

     select firstName from firstNames sample (1) where rownum =1; 

This is not an Oracle DB error code (they start with ORA- or ERR- or TNS- ). 这不是Oracle DB错误代码(它们以ORA-ERR-TNS-开头)。 It does look like a Derby error code. 它看起来确实像是Derby错误代码。 So did you use the wrong driver to access your oracle database, or do you actually mean JavaDB with "Oracle Database"? 那么,您使用错误的驱动程序访问了oracle数据库,或者您实际上将JavaDB与“ Oracle Database”一起使用? I guess the syntax is not valid for Derby/JavaDB. 我猜语法对于Derby / JavaDB无效。

According to this answer , the following syntax would work: 根据此答案 ,以下语法将起作用:

"SELECT firstName FROM firstNames ORDER BY RANDOM() OFFSET 0 ROWS FETCH NEXT 1 ROW ONLY"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM