My ads_man table has the following structure;
I want to select rows randomly from this table if column "rotate" is 1, otherwise if rotate = 0 then it shouldn't select these rows randomly. I've tried this;
$query = $db->query("
SELECT type,place,code
FROM ads_man
WHERE approved = '1' AND fid = '{$fid}' AND place = '{$zone}'
ORDER BY RAND()
LIMIT 3");
It selects the rows randomly but issue is I'm unable to find a quick way to select these rows rather to use another query to find all those rows having rotate = 1 and then use ORDER BY RAND()
in the query mentioned above.
Please help!
Try this;
$r_q = $db->query("SELECT rotate FROM ads_man");
$r = $db->fetch_array($r_q);
if($r['rotate'] == "1")
{
$rotate = 'rotate = "0" OR rotate = "1" AND';
$order_by = 'ORDER BY RAND()';
}
else
{
$rotate = 'rotate = "0" AND';
$order_by = 'ORDER BY dateline DESC';
}
$query = $db->query("
SELECT type,place,code
FROM ads_man
WHERE {$rotate} approved = '1' AND fid = '{$fid}' AND place = '{$zone}'
{$order_by}
LIMIT 3");
$query = $db->query("
SELECT type,place,code
FROM ads_man
WHERE rotate='1' AND approved = '1' AND fid = '{$fid}' AND place = '{$zone}'
ORDER BY RAND()
LIMIT 3");
I think it is better to add a random number column by ALTER
statement in given table. That will save lot of time.
There are several ways to do this:
It's not very clear what you need but, if you need 3 rows with rotate = 1
selected randomly and then others (for example 7) with rotate = 0
then you can do it with an UNION
(SELECT type,place,code
FROM ads_man
WHERE rotate = 1 AND approved = '1' AND fid = '{$fid}' AND place = '{$zone}'
ORDER BY RAND()
LIMIT 3)
UNION
(SELECT type,place,code
FROM ads_man
WHERE rotate = 0 AND approved = '1' AND fid = '{$fid}' AND place = '{$zone}'
LIMIT 7)
Is this what you need? Let me know if not
Edited: Forgot parenthesis