[英]select 1 random number from mysql database using asp.net c#
How can i select 1 random number from database thats ID is autoincrement field.I have 25,000[ID] records in database.Each every time select one new random ID. 如何从ID为autoincrement字段的数据库中选择1个随机数。我在数据库中有25,000个[ID]记录。每次选择一个新的随机ID。 How can get it.
如何得到它。
You can use the following query to generate a random number between 0 and COUNT
-1 of your table rows: 您可以使用以下查询来生成介于0到
COUNT
-1个表行之间的随机数:
SELECT ROUND((RAND() * (SELECT COUNT(*) FROM mytable)-1))
Then use this number as an offset in the LIMIT
clause of your query to get a random row from your table. 然后将此数字用作查询的
LIMIT
子句中的偏移量 ,以从表中获取随机行。
Using a prepared statement , you can do: 使用准备好的语句 ,您可以执行以下操作:
SET @offset = (SELECT ROUND((RAND() * (SELECT COUNT(*) FROM mytable)-1)));
PREPARE STMT FROM 'SELECT * FROM mytable LIMIT ?, 1';
EXECUTE STMT USING @offset;
Note that use of the prepared statement is mandatory since as documented in the manual : 请注意,由于本手册中所述,必须使用预处理语句:
LIMIT takes one or two numeric arguments, which must both be non-negative integer constants ( except when using prepared statements ).
LIMIT接受一个或两个数字参数,这两个参数都必须是非负整数常量 ( 使用prepared语句时除外 )。
Use following sql(slow) 使用以下sql(慢)
'SELECT * FROM tablename ORDER BY RAND() LIMIT 1'
or you can use(fast) 或者你可以使用(快速)
SELECT * FROM myTable, (SELECT FLOOR(MAX(myTable.id) * RAND()) AS randId FROM myTable) AS someRandId WHERE myTable.id = someRandId.randId
The inner SELECT gives you a random id in the right range. 内部SELECT为您提供正确范围内的随机ID。 The outer SELECT looks for the right row in the table.
外部SELECT在表中查找右行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.