- 问题是:我有更多的公司,我想做id_shutter" autoincrement"每个公司从1开始(id_company和id_shutter是复合PK)
CREATE FUNCTION insert_shutter() RETURNS TRIGGER AS $insert_shutter$
BEGIN
IF exists(select 1 from shutter where id_company=new.id_company) then
SELECT MAX(id_shutter) INTO new.id_shutter FROM shutter where id_company=new.id_company;
new.id_shutter:=id_shutter+1;
ELSE
new.id_shutter=1;
end if;
RETURN NEW;
END;
$insert_shutter$ LANGUAGE plpgsql;
CREATE TRIGGER insert_shutter
BEFORE INSERT ON shutter
FOR EACH ROW
EXECUTE PROCEDURE insert_shutter();
答案 0 :(得分:0)
偶尔这是必要的。但实际上,在表格中添加serial
列(让我们称之为ShutterId
)然后在检索数据时进行计算会更容易:
select s.*, row_number() over (partition by company order by id) as CompanyShutterSequence
from shutter s;
此外,调用带有重复值的id
内容会产生误导。
答案 1 :(得分:0)
抱歉我发现了,我无法使用:new.id_shutter:= id_shutter + 1; 我做了SELECT MAX(id_shutter)+1 INTO new.id_shutter FROM shutter其中id_company = new.id_company;