David19801
David19801

Reputation: 11448

mysql rand with condition

Could someone help me out with the correct syntax for this query please.

I have, table1:

id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

Upvotes: 0

Views: 234

Answers (4)

MRW
MRW

Reputation: 209

SELECT id, name FROM table1 WHERE `on` = 1 ORDER BY RAND() LIMIT 0,10;

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

SELECT `id`, `name` FROM `table1`
WHERE `on` = 1
ORDER BY RAND()
LIMIT 0,10

Use backticks to delimit field names. In this case you actually have to in the WHERE condition, because "ON" is a keyword.

Upvotes: 0

Marco
Marco

Reputation: 57573

This should work:

SELECT id,name FROM table1
WHERE `on`=1
ORDER BY RAND()
LIMIT 0,10

EDITED: as pointed out, column on could cause a syntax error without backticks

Upvotes: 2

Filip Krstic
Filip Krstic

Reputation: 713

Try this:

SELECT id,name FROM table1 WHERE `on`=1 ORDER BY RAND() LIMIT 0,10

Upvotes: 2

Related Questions