问题
I need to do a SQL call in a small local JavaDB in Netbeans 7.2 to pull a single random row from the database.
SELECT * FROM JAVA2.FORTUNES ORDER BY RANDOM()
So far, I've got it to work using the RANDOM() function, but I'm having trouble getting LIMIT 1 to work, it returns a syntax error.
I know that every database has a different way to do this, and I can't figure out how it works specifically for this JavaDB in Netbeans (I got it to work in a separate Oracle DB with different syntax).
Is there a Java DB specific, or ANSII standard way to return a single row using the above syntax?
回答1:
Java DB uses SQL's OFFSET/FETCH syntax to get this functionality.
Assuming RANDOM() orders them correctly the following syntax should work:
SELECT * FROM JAVA2.FORTUNES ORDER BY RANDOM() OFFSET 0 ROWS FETCH NEXT 1 ROW ONLY
回答2:
From http://db.apache.org/derby/faq.html#limit
Derby does not support the LIMIT syntax. However, Derby 10.4 added the ROW_NUMBER function and Derby 10.7 added the OFFSET and FETCH clauses.
Derby also supports limiting the number of rows returned by a query through JDBC. For example, to fetch the first 5 rows of a large table:
Statement stmt = con.createStatement(); stmt.setMaxRows(5); ResultSet rs = stmt.executeQuery("SELECT * FROM myLargeTable");
来源:https://stackoverflow.com/questions/15914204/how-to-use-the-sql-random-function-in-a-netbeans-javadb