Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a single random value from a database

How do i retrieve a single record from a data base but in a random manner? Any help you put forward will be highly appreciated. Thanks!

This is what i have done so far

protected void Button1_Click(object sender, EventArgs e)
{
    string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ahmed'susopriore'\Documents\Visual Studio 2013\Projects\WebApplication11\WebApplication11\Questions.accdb";
    OleDbConnection connection = new OleDbConnection(ConnectionString);
    Random rnd = new Random();
    rnd.Next();
    string myQuery = "SELECT * FROM Questions ORDER BY rnd()";
    OleDbCommand command = new OleDbCommand(myQuery, connection);
    try
    {
        connection.Open();
        OleDbDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
        ListBox1.Items.Add(reader["Number"]+"" );
        }
    }
    catch (Exception ex)
    {
        Label1.Text = "ERROR!"+ex;
    }
    finally
    {
        connection.Close();
    }
}
like image 358
user3052409 Avatar asked Aug 04 '26 22:08

user3052409


1 Answers

If primary key of questions is questionId Change your code from:

string myQuery = "SELECT * FROM Questions ORDER BY rnd()";

to:

string myQuery = "SELECT Top 1 * FROM Questions ORDER BY rnd(questionID)";

Or:

string myQuery = "SELECT Top 1 * FROM Questions ORDER BY Rnd(-(100000*questionID)*Time())
like image 178
Seyed Morteza Mousavi Avatar answered Aug 06 '26 12:08

Seyed Morteza Mousavi