Rand() by weight

code (weight)
(1) 30
(2) 20
(3) 35
(4) 10
(5) 5[/code]I have myTable like the above.

SELECT id FROM myTable ORDER BY rand() limit 1 The code above call (id) from 1 to 4 by random.

With the code above,
The record(1) will be called with the possibility of 20%.
The record(2) will be called with the possibility of 20%.
The record(3) will be called with the possibility of 20%.
The record(4) will be called with the possibility of 20%.
The record(5) will be called with the possibility of 20%.

I like to make it like the follow.
The record(1) will be called with the possibility of 30%.
The record(2) will be called with the possibility of 20%.
The record(3) will be called with the possibility of 35%.
The record(4) will be called with the possibility of 10%.
The record(5) will be called with the possibility of 5%.

How can I make it as what I want?
if there is some problems in the table for getting my target result, How should I change the table structure for making the result what I want?

SELECT t.id , t.weight , n.n FROM joon2 AS t CROSS JOIN numbers AS n WHERE n.n BETWEEN 1 AND t.weight ORDER BY RAND() LIMIT 1

[code] $query=“SELECT t.id
, t.weight
, n.n
FROM myTable4 AS t
CROSS
JOIN numbers AS n
WHERE n.n BETWEEN 1 AND t.weight
ORDER
BY RAND() LIMIT 1”;

$sql=mysql_query($query); $row=mysql_fetch_assoc($sql); $id=$row[‘id’];[/code]
I am afraid the code above produces an error, saying like the follow.

no, that’s not possible

the code i gave you is sql, but you posted a php error

run the query outside of php, please

1 Like

The error that the OP is getting is as a result of the query failing (the mysql_query() retuned false as the query failed meaning that the mysql_fetch_assoc() recieved false instead of a result set which it expects.

btw @joon1 are you aware that the mysql_* extension was removed from PHP as of version 7 of PHP. You need to be migrating to either the mysqli_* extension (nite the “i” in there) or PDO

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.