0
votes

Please I am trying to get data from MySQL database in a random order but it seems to return result in duplicates.

Is there a way I can get Data in a random order while following id and not getting duplicate results.

For instance I have a database table users with 4 unique users inside.

  • user1

  • user2

  • user3

  • user4

Then I try this query

SELECT username from users ORDER BY RAND() LIMIT 3

I tend to receive User1, User2 User1

Whereas I hope to get User2, User1, User3 as result.

Is there anyway I can achieve this?

I believe you understand and I hope this is not offtopic im grateful for any response i can get.

Thanks.

1
Can you show SQLFiddle of the setup you have? Your query should not return same rows more than once as the ORDER BY mererly sorts an existing result set which does not have duplicates in it. - slaakso
lol, why would you like to do this? - André Pletschette
@andré I'm working on a project that I need to fetch posts random ly joining several tables together. But on frontend it returns the same rows twice - Freesoul
@slaakso I have no idea how I can do that but I'm happy to share my real query with you - Freesoul
Create a sample in db-fiddle: db-fiddle.com - slaakso

1 Answers

0
votes

You may try DISTINCT keyword -

SELECT DISTINCT username
FROM users
ORDER BY RAND()
LIMIT 3