从联合中选择随机值

时间:2014-08-08 17:45:13

标签: mysql sql random

我有以下查询(我将省略绑定以澄清事情):

(select * 
from advertisements 
where city_id is null and 
category_id is null order by RAND() asc limit 1) 

 union 

(select * 
from advertisements 
where city_id = ? and 
category_id is null) 

union 

(select * 
from advertisements where 
category_id = ? and 
city_id = ?) 

union

(select * 
from advertisements 
where city_id is null and 
category_id = ?)

如何从所选行中选择随机行?即有3个工会。如果查询返回5行,我应该如何修改此查询,以便从那些5?

返回一个随机行

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

select * from (select * from advertisements where city_id is null and category_id is null order by RAND() asc limit 1) union (select * from advertisements where city_id = ? and category_id is null) union (select * from advertisements where category_id = ? and city_id = ?) union (select * from advertisements where city_id is null and category_id = ?) as x
ORDER BY RAND()
LIMIT 1

答案 1 :(得分:0)

再次选择所选行:

SELECT * 
FROM (
    (select * 
    from advertisements 
    where city_id is null and 
    category_id is null order by RAND() asc limit 1) 

     union 

    (select * 
    from advertisements 
    where city_id = ? and 
    category_id is null) 

    union 

    (select * 
    from advertisements where 
    category_id = ? and 
    city_id = ?) 

    union

    (select * 
    from advertisements 
    where city_id is null and 
    category_id = ?)
    ) AS d
ORDER BY RAND() ASC
LIMIT 1