Page 1 of 1
Forcing a set number of results
Posted: Fri May 19, 2006 8:25 pm
by GeXus
I'm trying to do a look up where keyword = keyword.. but I would like to force at least 2 results to always be returned.. so there may be only be 1 or maybe 0 matches, if that is the case, it should just return any 2...
Is this posible on the sql end?
Posted: Sat May 20, 2006 12:31 am
by RobertGonzalez
It is possible, but I think you will either need a user defined function or something like stored procedures. I'm not sure a straight query will be able to identify if there are two or more of something and pull them, else pull any two if less than two.
Posted: Sat May 20, 2006 3:43 am
by s.dot
Code: Select all
$result = mysql_query("SELECT count(*) FROM `table` WHERE `foo` = '$bar'") or die(mysql_error());
if(mysql_result($result,0) < 2){
$result = mysql_query("SELECT `something` FROM `table` ORDER BY RAND() LIMIT 2");
} else {
$result = mysql_query("SELECT `something` FROM `table` WHERE `foo` = '$bar' LIMIT 2");
}
Posted: Sat May 20, 2006 2:05 pm
by GeXus
scottayy wrote:Code: Select all
$result = mysql_query("SELECT count(*) FROM `table` WHERE `foo` = '$bar'") or die(mysql_error());
if(mysql_result($result,0) < 2){
$result = mysql_query("SELECT `something` FROM `table` ORDER BY RAND() LIMIT 2");
} else {
$result = mysql_query("SELECT `something` FROM `table` WHERE `foo` = '$bar' LIMIT 2");
}
THANK YOU!
Posted: Sat May 20, 2006 3:34 pm
by GeXus
Ok im stumped!
So, now I'm able to determine if not enough results are returned, I can return random results.. But what if say 1 result was returned.. how would I display that result AND a random result, to make up for the limit 2.. and order it by the non-random result..

Posted: Sat May 20, 2006 5:24 pm
by GeXus
Ok i figured this one out.. by doing a UNION it worked perfect..
thanks again!