在 PostgreSQL 中使用 WHERE 子句执行 TABLESAMPLE

Rev*_*lle 7 postgresql query random table where

我想使用 TABLESAMPLE 从 PostgreSQL 满足特定条件的行中随机采样。

这运行良好:

select * from customers tablesample bernoulli (1);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将条件嵌入脚本中。例如这个

select * from customers where last_name = 'powell' tablesample bernoulli (1);
Run Code Online (Sandbox Code Playgroud)

抛出这个错误:

SQL 错误 [42601]:错误:“tablesample”位置或附近的语法错误
:71

小智 9

tablesample是表的“属性”,而不是查询。所以需要写在表名后面:

select * 
from customers tablesample system (1)
where last_name = 'powell';
Run Code Online (Sandbox Code Playgroud)

请注意,该子句将在对表进行采样where应用。它不会返回姓氏为“powell”的所有客户的 1%。但它会将过滤器应用于采样表。

  • @reveille不,它被称为tablesample而不是rowsample是有原因的。您只需添加“and random()<0.01”或“order by random() limit ...” (3认同)