【发布时间】:2018-03-21 04:40:44
【问题描述】:
我有两个表 vendor_service_place 和 places.id 作为 vendor_service_table 中的外键。我创建了一个过程,它首先将一个条目插入到位置表中,然后从 LASTVAL() 中获取该 ID 并将一个条目插入到 vendor_service_table 中。但是当我执行这个功能时,我得到了
insert or update on table "vendor_service_place" violates foreign key
constraint "fk_places"
DETAIL: Key (place_id)=(2057) is not present in table "places".
CONTEXT: SQL function "insert_data" statement 2
这是我的插入过程:
CREATE FUNCTION insert_data(vendorid integer,
serviceid integer,
name text,
address text,
latitude text,
longitude text,
contact_info text,
rating numeric,
description text) RETURNS bigint AS $$
INSERT INTO places(name,address,latitude,longitude,contact_info,created_at)
VALUES (name,address,latitude,longitude,contact_info,current_timestamp);
INSERT INTO vendor_service_place(vendor_id,service_id,place_id,description,rating,created_at)
VALUES (vendorid,serviceid,LASTVAL(),description,rating,current_timestamp);
SELECT LASTVAL() as result;
$$ LANGUAGE SQL;
我怀疑 Postgres 执行某种批处理,它同时执行这两个语句,这可能是它无法在位置表中找到 id 的原因。有关如何正确执行此操作的任何想法?
【问题讨论】:
-
请edit您的问题并为表格
places添加create table声明 -
LASTVAL()是什么? -
@joop:
lastval()返回最后生成的序列值:postgresql.org/docs/current/static/functions-sequence.html -
我不知道它可以在没有任何参数的情况下使用。对我来说似乎是个坏习惯......
标签: postgresql stored-procedures