这在纯 SQL 中很难做到。我会求助于plpgsql程序。
比方说,你的表格是这样的:(
下次,最好发布一个表格定义。价值超过一千字。)
create table p (
id serial primary key -- or whatever your primary key is!
, company_id int4 NOT NULL
, create_time timestamp NOT NULL
, for_sale bool NOT NULL
);
使用这样的 plpgsql 函数:
CREATE OR REPLACE FUNCTION f_p_group()
RETURNS void AS
$BODY$
DECLARE
g_id integer := 1;
last_time timestamp;
last_company_id integer;
r p%ROWTYPE;
BEGIN
-- If the table is huge, special settings for these parameters will help
SET temp_buffers = '100MB'; -- more RAM for temp table, adjust to actual size of p
SET work_mem = '100MB'; -- more RAM for sorting
-- create temp table just like original.
CREATE TEMP TABLE tmp_p ON COMMIT DROP AS
SELECT * FROM p LIMIT 0; -- no rows yet
-- add group_id.
ALTER TABLE tmp_p ADD column group_id integer;
-- loop through table, write row + group_id to temp table
FOR r IN
SELECT * -- get the whole row!
FROM p
-- WHERE for_sale -- commented out, after it vanished from the question
ORDER BY company_id, create_time -- group by company_id first, there could be several groups intertwined
LOOP
IF r.company_id <> last_company_id OR (r.create_time - last_time) > interval '10 min' THEN
g_id := g_id + 1;
END IF;
INSERT INTO tmp_p SELECT r.*, g_id;
last_time := r.create_time;
last_company_id := r.company_id;
END LOOP;
TRUNCATE p;
ALTER TABLE p ADD column group_id integer; -- add group_id now
INSERT INTO p
SELECT * FROM tmp_p; -- ORDER BY something?
ANALYZE p; -- table has been rewritten, no VACUUM is needed.
END;
$BODY$
LANGUAGE plpgsql;
调用一次,然后丢弃:
SELECT f_p_group();
DROP FUNCTION f_p_group();
现在,根据您的定义,组的所有成员共享一个group_id
.
问题编辑后编辑
我又添加了一些东西:
- 将表读入临时表(在过程中排序),在那里进行所有更新,截断原始表添加 group_id 并一次性从临时表中写入更新的行。应该更快,之后不需要真空。但是你需要一些内存
for_sale
在不再出现问题后在查询中被忽略。
- 阅读有关%ROWTYPE的信息。
- 在此处阅读有关work_mem 和 temp_buffers的信息。
- TRUNCATE, ANALYZE, TEMP TABLE, ALTER TABLE, ...全部在精美手册中
- 我用 pg 9.0 测试了它。应该在 8.4 - 9.0 和可能更旧的版本中工作。