我想在PostgreSQL中编写一个程序,为我提供一些选定表的随机记录。我怎样才能做到这一点?我在网上找不到任何好的教程...
我知道我可以从PostgreSQL以多种方式获取随机记录。但我有很大的表,其中大多数都会导致性能问题。我也想学习一些新东西。
答案 0 :(得分:0)
SELECT * FROM my_table
ORDER BY random() LIMIT 10;
答案 1 :(得分:0)
我完成了类似的事情:
CREATE OR REPLACE FUNCTION get_random_id(in_table_name TEXT, want_elements INT4) RETURNS INT4[] as $BODY$
declare
use_sql TEXT;
id_range record;
reply INT4[];
this_part INT4[];
try INT4 := 0;
i INT4;
BEGIN
use_sql := 'SELECT min(id), max(id) - min(id) + 1 as range FROM ' || quote_ident(in_table_name);
EXECUTE use_sql INTO id_range;
IF id_range.range < want_elements THEN
raise exception 'not enough elements in % table.', in_table_name;
END IF;
WHILE ( try < 10 ) LOOP
try := try + 1;
this_part := '{}'::INT4[];
WHILE ( coalesce(array_upper( this_part, 1 ), 0) < want_elements - coalesce(array_upper(reply, 1), 0)) LOOP
i := floor( random() * id_range.range) + id_range.min;
IF NOT i = ANY(this_part) THEN
this_part := this_part || i;
END IF;
END LOOP;
use_sql := 'SELECT id FROM ' || quote_ident(in_table_name) || ' WHERE id = ANY(' || quote_literal(this_part::TEXT) || '::INT4[])';
for i IN EXECUTE use_sql LOOP
reply := reply || i;
END LOOP;
IF (coalesce(array_upper(reply, 1), 0) = want_elements) THEN
RETURN reply;
END IF;
END LOOP;
RAISE EXCEPTION 'something strange happened - requested records not found in % tries', try;
END;
$BODY$ language plpgsql STABLE;
但是这个功能有一个问题。当我像这样使用它时:
select first_name from people WHERE (difference(first_name, 'first_name') < 2) and id = any(get_random_id('people', 3));
它有时会返回3条记录,有时会返回2或1 ...... :(