Jump to content

MySQL Random Number Problem


mmcb

Recommended Posts

Hello again,

I have a new problem for you all. I have a MySQL table and want to return certain records (no problem), but I also want MySQL to generate a random number. This is what I'm using:
[code]SELECT DesignID, DesignName, (FLOOR(1 + RAND() * 12)) AS Location FROM `tbldesigns` WHERE MenuID="something";[/code]

This works except that I sometimes get duplicates in the "Location" field. Is there anyway to do the same thing without getting duplicates?

Cheers,
MMCB
Link to comment
https://forums.phpfreaks.com/topic/35581-mysql-random-number-problem/
Share on other sites

I would suggest doing the random numbers in the PHP after you get the results. Assuming you will be looping through the records to display/act on them you could do something like this:

[code]<?php
$randNumbers = array();
while ($row = mysql_fetch_array($results)) {
  $newNo="";
  while ($newNo=="" || in_array ($newNo, $randNumbers)) {
    $newNo = rand(1,12);
  }
  $randNumbers[] = $newNo;
  //Display row resultrs and the random number
}
?>[/code]

Of couorse you would get stuck in an infinite loop if there were more than 12 results, so you would want to add an exception handler for that.
[quote author=snowrhythm link=topic=123897.msg512751#msg512751 date=1169677349]yeah, you also might want to throw in a "DINSTINCT" in front of  "LOCATION" in the SQL string...[/quote]
DISTINCT won't work in this situation as it is not a field he is pulling from the table. I tried it out of curiosity and no go.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.