For this, use RAND() for random records and LIMIT 1 to get only a single value. However, use the WHERE clause to select that particular ‘Name’, which is repeating.
Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20) ); Query OK, 0 rows affected (1.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('Chris'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(Name) values('Bob'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Name) values('David'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(Name) values('Bob'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Name) values('Bob'); Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------+ | Id | Name | +----+-------+ | 1 | Chris | | 2 | Bob | | 3 | David | | 4 | Bob | | 5 | Bob | +----+-------+ 5 rows in set (0.65 sec)
Following is the query to fetch a random value −
mysql> select *from DemoTable where Name='Bob' order by rand() limit 1;
This will produce the following output −
+----+------+ | Id | Name | +----+------+ | 5 | Bob | +----+------+ 1 row in set (0.00 sec)