0

I have a sample code

products(id, name)
1 | Apple
2 | Sony
3 | Nokia
4 | Samsung
5 | LG
6 | Motorola
7 | Ekricson

And mysql:

SELECT id, name FROM `products` AS prod 
ORDER BY RAND(prod.id) LIMIT 5

When i run code is result is:

4 | ...
7 | ...
1 | ...
5 | ...
6 | ...

But next ... is result is:

4 | ...
7 | ...
1 | ...
5 | ...
6 | ...

Id not change when run random, how to fix ix

1
  • try taking out the prod.id from RAND() the argument is the seed value which is used to generate a repeatable sequence of numbers. (according to the documentation) Commented Jun 29, 2012 at 9:22

5 Answers 5

7

You should use ORDER BY RAND() and not ORDER BY RAND(prod.product_id)

From RAND manual:

RAND(), RAND(N)

Returns a random floating-point value v in the range 0 <= v < 1.0.
If a constant integer argument N is specified, it is used as the seed value
which produces a repeatable sequence of column values.
Sign up to request clarification or add additional context in comments.

Comments

1

The argument inside the RAND(x) function is the seed, so you're seeding it with the same value every time. Instead, leave it as RAND() and it will be different.

Comments

0

SELECT id, name FROM products AS prod ORDER BY RAND() LIMIT 5

Comments

0

You probably want just ORDER BY RAND() rather than ORDER BY RAND(prod.id) -- if you give RAND() an integer argument, it's used as the seed value, so you will always get the same "random" value back.

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

Comments

0

Use this way:

SELECT id, name FROM `products` AS prod 
ORDER BY RAND() LIMIT 5;

See manual here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.