如何从MS Access数据库中选择随机行?
你好。
我正在开发一个圣经琐事游戏。
我有一个带QUESTIONID(整数)的QUESTIONS表,QUESTIONSTMT (字符串)2列,以及其中的一些行。我想选择随机的10个问题来执行游戏。
我搜索了一些页面,并看到了一个解决方案:
Hello.
I am developing a holy bible trivia game.
I have a QUESTIONS table with QUESTIONID(integer),QUESTIONSTMT(string) 2 columns, and some rows in it. I want to select random 10 questions for executing the game.
I've searched some page, and see a solution:
SELECT TOP n * FROM Table WHERE [conditions] ORDER BY RND([number col])
但是当我使用时在我的代码中,它抛出一个异常,我没有为参数赋值。
我怎么能解决这个问题?
but when I use it in my code, it throws an exception that I didn't give a value for a parameter.
How could I solve this problem?
你可以使用这样的东西
You could use something like this
SELECT TOP 10 QUESTIONID,QUESTIONSTMT FROM QUESTIONS ORDER BY RND(1217*QUESTIONID)
1217只是一个数字,可以是零以外的任何数字。
1217 is just a number, could be anything except zero.
尝试ORDER BY new guid(你必须查找如何为Access生成新的GUID)。它将每次生成唯一的guid,从而以随机方式对您的前n个查询进行排序。
如果这有帮助,请花时间接受解决方案。谢谢。
Try ORDER BY new guid (you'll have to look up how to generate new GUID for Access). It will generate unique guid each time and thus sort your top n query in random fashion.
If this helps please take time to accept the solution. Thank you.
请查看您的查询:
Please, have a look at your query:
SELECT TOP n *
FROM Table
WHERE [conditions]
ORDER BY RND([number col])
我看到几个问题:
1)如果 n
是参数,你需要定义它(见下文)。
2)表
是保留字 [ ^ ]。我建议更改表名。
3) [条件]
- 能够使用 WHERE语句 [ ^ ],你应该至少提供一个列名和比较运算符
I see few issues:
1) If n
is parameter, you need to define it (see below).
2) Table
is reserved word[^]. I'd suggest to change the table name.
3) [conditions]
- to be able to use conditions in WHERE statement[^], you should provide at least a column name and comparison operator
WHERE ColumnName <operator> [condition]
4) RND([number col])
未知MS Access,因为 Rnd [ ^ ]不接受任何输入参数。
顺便说一下: ORDER BY声明 [ ^ ]参数的行为类似于 WHERE
声明。
所以...
如果你想获得10个随机数,您需要编写一个查询,如下所述:
如何在Microsoft的SQL查询中创建随机数访问? [ ^ ]
在查询中创建一个randon唯一编号字段 [ ^ ]
4) RND([number col])
is not known for MS Access, because Rnd[^] does not accept any input parameter.
By The Way: ORDER BY statement[^] with parameters behaves like WHERE
statement.
So...
If you want to get 10 random numbers, you need to write a query, as is described here:
How to create a random number in an SQL query on Microsoft Access?[^]
Create a randon unique number field in a query[^]