Select a random row from the table, but with a coefficient?

I have a table that describes a lot of objects in my system (i.e. an umbrella, boots, bag, whatever). Each of these objects should have a clear prevalence or incidence. For example, an umbrella is less common than boots. Based on these factors, I need to randomly select one object (including an empty or "not found object") based on this incident value.

Clap. It makes sense?

+3
source share
3 answers

I am going to change the symcbean response for this, +1 for symcbean.

SELECT * FROM some_table
WHERE (100*RAND()) < some_table.percent_probability

, , . , 5 20 20% . 90 90% .

, , . . :

$items = array(); // assuming you've already filled $items with your 
                  // query results, one item for each array key

$count = count($items);

$chosen_key = rand(1,$count)-1;

$chosen_item = $items[$chosen_key];
0
SELECT * FROM some_table
WHERE (100*RAND()) > some_table.percent_probability
LIMIT 1

.... percent_probability.

.

+1

(.. ), , , , , ( , , ).

. ( per-mill)
: 500 ‰
: 250 ‰
: 100 ‰
: 100 ‰
"": 50 ‰

0 499 , "" , 500-749 "" ..

INSERT INTO foo (name, randmin, randmax) VALUES
  ('umbrella', 0, 499),  
  ('boots', 500, 749),
  ('satchel', 750, 849), 
  ('whatever', 850, 949) 

, , .

SELECT
  f.name
FROM
  (  
    SELECT Round(Rand()*1000) as r    
  )  as tmp
JOIN
  foo as f  
ON
  r BETWEEN f.randmin and f.randmax  
LIMIT
  1

, MySQL (randmin, randmax), .

+1

Source: https://habr.com/ru/post/1739210/


All Articles