简体   繁体   中英

Insert random number with mysql

i have a question in regards to mysql mainly. i have the following:

mysql_query("INSERT INTO {$game}_ships (location,login_id
         ) values(
    '250','44')");

i would like to make the location a random number from 2 to 300.

my table structure includes among others a column for location and login id, i dont need to mention other columns as they are static and do not change. the above is suposed to make a ship look like its moving around the systems.

location   int(4)

can anyone help with this?

mysql_query("INSERT INTO {$game}_ships (location,login_id
         ) values(
    FLOOR(RAND() * 298 + 2),'44')");

See: http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand

You can use something like this:

INSERT INTO TABLE_NAME(rand_col) VALUES(FLOOR($MIN_VAL + (RAND() * ($MAX_VAL - $MIN_VAL))));

Where MIN_VAL is your lower number (2) and MAX_VAL is your higher number(300)

您可以改用PHP的rand吗?

mt_rand(2,300)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM