I have 3 identically structured tables called low, med, high. I would like to randomly choose one table from these tables, then query that table.
visual example:
SELECT * FROM RAND(low,med,high)
I have 3 identically structured tables called low, med, high. I would like to randomly choose one table from these tables, then query that table.
visual example:
SELECT * FROM RAND(low,med,high)
You may use a union approach which assigns a computed value of 1, 2, or 3, to each of the three tables, then randomly choose the records from just one table:
SELECT *
FROM
(
SELECT *, 1 AS label FROM low UNION ALL
SELECT *, 2 FROM med UNION ALL
SELECT *, 3 FROM high
) t
WHERE label = FLOOR(RAND()*3+1); -- random number between 1 and 3 inclusive
You used the PHP tag, so in that language it can be like this:
$tables = ['low', 'med', 'high'];
$randomTable = $tables[mt_rand(0, 2)];
$query = 'SELECT * FROM '.$randomTable;
$mysqli = new mysqli("host","my_user","my_password","my_db");
$result = $mysqli -> query( $query);
In MySQL, in addition to the other solutions, it can be like this:
Select the table randomly:
set @randomNumber = FLOOR(RAND()*3+1);
set @table = IF(@randomNumber = 1, 'low', IF(@randomNumber = 2, 'med', 'high'));
or
set @table = CASE
WHEN @randomNumber = 1 THEN 'low'
WHEN @randomNumber = 2 THEN 'med'
ELSE 'high'
END;
Build and run the query:
SET @s = CONCAT('select * from ', @table);
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
select * from high
union all
select * from med
union all
select * from low
order by rand()
limit 1