# Optimisation for random generator code in PHP [closed]

I'm really confused about combining MySQL queries and please could you lend me a hand? Please explain in simple English. The code is:

    $result1 = mysql_fetch_assoc(mysql_query("SELECT COUNT( * ) AS Rows , 1 FROM things GROUP BY 1 ORDER BY RAND() LIMIT 0 , 1"));$result2 = mysql_fetch_assoc(mysql_query("SELECT COUNT( * ) AS  Rows ,  2 FROM  things GROUP BY  2 ORDER BY RAND() LIMIT 0 , 1"));
$result3 = mysql_fetch_assoc(mysql_query("SELECT COUNT( * ) AS Rows , 3 FROM things GROUP BY 3 ORDER BY RAND() LIMIT 0 , 1"));$result4 = mysql_fetch_assoc(mysql_query("SELECT COUNT( * ) AS  Rows ,  4 FROM  things GROUP BY  4 ORDER BY RAND() LIMIT 0 , 1"));

echo "$result1[1]"; echo " "; echo "$result2[2]";
echo " ";
echo "$result3[3]"; echo " "; echo "$result4[4]";

-

## closed as off topic by Jeff Vanzella, Glenn Rogers, palacsint, Bobson, Brian ReichleJan 30 '13 at 20:55

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

In relation to your title: :) Do get random numbers in PHP use rand()

In relation to your post: You are picking a random value of the columns 1-4 and you count the number of distinct values in columns 1-4. The later you ignore, so we can reduce the query to:

SELECT  1 FROM  things GROUP BY  1 ORDER BY RAND() LIMIT 0 , 1


If you want to have all 4 random values in one query you can use UNION.

(SELECT  1 as x FROM  things GROUP BY  1 ORDER BY RAND() LIMIT 0 , 1)
UNION
(SELECT  2 as x FROM  things GROUP BY  2 ORDER BY RAND() LIMIT 0 , 1)
...


Please let us know what you are going to do. This does not sound like a common scenario.

If you just want to concat the string with a random values of each column you could also do this directly in mysql (although this is a really strange use case):

SELECT CONCAT(x.1," ",y.2) as w FROM
(SELECT  1 as x FROM  things GROUP BY  1 ORDER BY RAND() LIMIT 0 , 1) as x,
(SELECT  2 as x FROM  things GROUP BY  2 ORDER BY RAND() LIMIT 0 , 1) as y,
...

-