开发者

mysql random with condition

I have a table in mysql, say table1.

I am running this on it:

SELECT FLOOR( MAX(id) *开发者_运维百科 RAND()) FROM `table1`

This works well, but I am now trying to add a condition of "AND tom".

Where tom is a integer field.

For example:

id tom
1   0
2   3
3   2
4   0
5   0
6   3
7   1
8   1
9   3

etc.

So, my question is,

How can I pick a random value from id, which also satisfies tom='0' say?


SELECT id FROM `table1` WHERE tom = 0 ORDER BY RAND() LIMIT 1

This will first get all rows in which tom = 0,then order those results randomly. MySQL will then limit those results to just one, returning the single value you want to retrieve.


I hope I understood correctly:

SELECT id FROM `table1` WHERE tom = 0 order by rand() limit 1


select * from (
select * from table where tom = 0 ) as t order by rand() limit 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜