MySQL get a random value between two values

前端 未结 5 1245
日久生厌
日久生厌 2020-12-03 01:01

I have two columns in a row: min_value, max_value. Is there a way to do a select like:

SELECT RAND(`min_v`, `max_v`) `foo` [..]
         


        
5条回答
  •  时光说笑
    2020-12-03 01:22

    Actually, ROUND((RAND() * (max-min))+min) is the best way in MySQL to do what you'd like. It is also the best way in ActionScript, JavaScript, and Python. Honestly, I prefer it to the PHP way because it is more convenient.

    Because I don't know how many rows you'll be returning, I can't advise you whether it is better to use PHP or MySQL for this, but if you're dealing with a large number of values you probably are better off using MySQL.

    Addendum


    So, there was a question as to whether this is better in PHP or MySQL. Instead of getting into a debate on principles, I ran the following:

    MySQL is faster by about 2-3%.

    If you use this, however (note, more columns return by MySQL):

    MySQL comes out behind by 3-4% (very inconsistent results) (about the same results if you don't use an array index assignment for $r[2]).

    The major difference, it seems, comes from the number of records return to PHP and not the randomization system itself. So, if you need column A, column B, and a random value, use PHP. If you only need the random value, then use MySQL.

提交回复
热议问题