mysql order by rand limit 1 really slow

Solutions on MaxInterview for mysql order by rand limit 1 really slow by the best coders in the world

showing results for - "mysql order by rand limit 1 really slow"
Lilly
18 Mar 2019
1function get_random_row($mytable,$conn){
2	$table_max_id = $conn->query("SELECT id FROM $mytable ORDER BY id DESC LIMIT 0, 1")[0]["id"];
3	$rand_id=rand(1,$table_max_id);
4	$random_result = $conn->query("select * from $mytable where id = $rand_id");
5  	
6	#note: if you are missing some id's, we can call again until we get hit
7  	if(!$random_result){
8    	return get_random_row($mytable,$conn);
9    }
10  
11  	return $random_result;
12}