1

I want to get random row from database, but limit it using some content.

For example, table's definition:

id | content | tags

The query is: SELECT * FROM tbl ORDER BY RAND() LIMIT 1.

Tags part looks like: tag1, tag2, tag42. So, for example, I want one random row from ones which have tag42 or tag2 inside tags.

Some pseudocode:

SELECT * FROM tbl ORDER BY RAND() WHERE tags LIKE '%tag42%' OR '%tags2%' LIMIT 1.

Jack Pettinger
  • 2,715
  • 1
  • 23
  • 37
Max Frai
  • 61,946
  • 78
  • 197
  • 306

1 Answers1

3

Your pseudocode is almost correct, except you have order of clauses wrong: WHERE comes before ORDER BY

SELECT * FROM tbl WHERE tags LIKE '%tag42%' OR '%tags2%' ORDER BY RAND() LIMIT 1

See the documentation for SELECT syntax, to never get wrong again

Mchl
  • 61,444
  • 9
  • 118
  • 120