How to return sample row from database one by one

别等时光非礼了梦想. 提交于 2019-12-01 14:03:17

An order by will always be expensive specially if the expression in the order by is not indexed. So don't order. In instead do a random offset in the count() as in your queries, but do it all at once.

with t as (
    select *
    from
        products p
        inner join
        images i using (productid)
    where
        prodtype = $sometype
)
select *
from t
offset floor(random() * (select count(*) from t))
limit 1

This version might be faster

with t as (
    select *, count(*) over() total
    from
        products p
        inner join
        images i using (productid)
    where
        prodtype = $sometype
)
select *
from t
offset floor(random() * (select total from t limit 1))
limit 1

PosgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

This gives you one, random row. You can of course add back in your WHERE filter to make sure it is the right category.

This removes your requirement to do a count first; and also has the advantage of letting the database engine do the selection, reducing round trips.

Note: For people looking at ways to do this in other SQL engines: http://www.petefreitag.com/item/466.cfm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!