There is no particularly wonderful way to do this elegantly.
But you can crack it in several ways. If your dataset is the right size (too big for "order by rand ()" but not too big), have consistent identifier values ββand usually don't delete a lot, you can always do something like this:
SELECT MIN(id) as min, MAX(id) as max FROM table
Generate some number N of random numbers between "min" and "max" (inclusive). Let me call it 50. If you never delete anything from the table, N will probably be 12. If you delete, do some napkin arithmetic and choose a good number. You are probably mistaken on the high side.
SELECT * FROM table WHERE id IN (<your set of integers>) AND image_id = '' LIMIT 12;
Make sure you have at least 12 results. If not, basically repeat and combine.
For large sets, this method should work much better than ORDER BY RAND (), especially if your identification sequence is not very sparse.
source share