简体   繁体   English

PostgreSQL-随机顺序与不同

[英]PostgreSQL - Random order with Distinct on

I am trying to return products in random order (or descending order) and have a button that gets more random products that are NOT part of previous random products. 我正在尝试以随机顺序(或降序)退回产品,并有一个按钮可以获取不属于先前随机产品的更多随机产品。 Basically if I have 15 products total, I want 3 random products, and then click button and get 3 more random items and so on until there are no more items. 基本上,如果我总共有15个产品,我想要3个随机产品,然后单击按钮并获得3个随机项目,依此类推,直到没有更多项目为止。

I have a pretty whack query going on to get data from my tables. 我正在进行一个漂亮的查询,以从表中获取数据。

I'm using the ' DISTINCT on ' to get one product and show it's lowest price (without it, it will list the product for however many prices it has). 我正在使用“ DISTINCT on ”来获得一种产品并显示其最低价格(没有价格,它将列出具有多种价格的产品)。 I know that it is effecting the random ordering / descending ordering. 我知道这会影响随机排序/降序排序。

SELECT DISTINCT on (products.id) products.*, prices.price FROM products
INNER JOIN product_price_size ON products.id = product_price_size.productId
INNER JOIN prices ON prices.id = product_price_size.priceId
WHERE active = true AND (archived IS NULL OR archived = false)
ORDER BY products.id, prices.price LIMIT 3

The 'get more products' button is basically the same query with OFFSET being a variable after LIMIT 3 “获取更多的产品”按钮基本上是随偏移距LIMIT 3后的变量相同的查询

Hopefully this makes sense. 希望这是有道理的。 Does anyone have an idea on how to achieve what I'm trying to get? 有人对如何实现我想要获得的想法有想法吗?

Thanks! 谢谢!

You can keep incrementing the offset of a stable ordering. 您可以继续增加稳定顺序的偏移量。 One ordering might be based on a deterministic hash like md5 (change some_random_salt for a new ordering): 一种排序可能基于诸如md5类的确定性哈希(更改some_random_salt为新的排序):

select id from tbl
order by md5(id || 'some_random_salt'), id
limit 3 offset ?

Or the modulo of prime number (change the prime number for a different ordering): 或素数的模(更改素数以不同的顺序):

select id from tbl
order by id % 11, id
limit 3 offset ?

Then increment the offset: 然后增加偏移量:

[...]
limit 3 offset 3

[...]
limit 3 offset 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM