Inserting random value into a mysql database
I have 52 items which I randomly insert into a database with the help of the php rand function.
Each item has an ID from 1 - 52, and also has a value. Every 13 items has a value of 1 - 13. E.g.
Items 1 - 13 have values of 1 - 13, while items 14 - 26 also have values 1 - 13, and so on until the last item, 52. How would I ensure that the value is correct upon insertion to the database? I would imagine the modulus is involved? I guess 开发者_高级运维this is more of a math question than database!
If you want to do this purely in SQL, I would do it as follows
First define a table that lists the values you want, in order.
CREATE TABLE cards (
id int auto_increment,
card int,
PRIMARY KEY(id)
);
INSERT INTO cards(card) VALUES(....);
Now you can create a randomized table like this
CREATE TABLE shuffled (
id int auto_increment,
card int,
PRIMARY KEY(id),
)
SELECT 0,card FROM cards ORDER BY RAND();
This sounds like you are shuffling a deck of cards. I believe there is a function shuffle() that does what you want (if you are using PHP)
If this is just a request for code to do it, then obviously my answer is bad. Also, if you want to do it only in SQL, this is a bad answer.
Since you know the id in PHP,
$value = $id % 13;
if ($value == 0) $value = 13;
The %
operator (also known as modulus) gives us the remainder when x is divided by y.
The second line gives us 13 instead of 0 for multiples of 13, since modulus will return 0, but we want 13 instead.
精彩评论