我有以下数据库结构:
CREATE TABLE songs (_id SERIAL PRIMARY KEY, _artist TEXT, _name TEXT);
CREATE TABLE cafes (_id SERIAL, _ip TEXT PRIMARY KEY);
CREATE TABLE users (_id SERIAL UNIQUE, _imei TEXT PRIMARY KEY);
CREATE TABLE votes (_id SERIAL PRIMARY KEY, _cafe TEXT, _user INTEGER, _song INTEGER, _vote INTEGER);
我有一个存储过程来检查某些行是否存在,如果它们不存在则创建它们 存储过程:
CREATE OR REPLACE FUNCTION testfunc(user_imei text, cafe_ip text, song_artist text, song_name text) RETURNS void AS $$
DECLARE
id_cafe INTEGER;
id_user INTEGER;
id_song INTEGER;
temp_row RECORD;
BEGIN
IF NOT EXISTS (SELECT _id FROM users WHERE _imei = user_imei) THEN
insert into users (_imei) values (user_imei);
END IF;
IF NOT EXISTS (SELECT _id FROM cafes WHERE _ip = cafe_ip) THEN
insert into cafes (_ip) values (cafe_ip);
END IF;
IF NOT EXISTS (SELECT _artist FROM songs WHERE _artist = song_artist AND _name = song_name) THEN
insert into songs (_artist, _name) values (song_artist, song_name);
END IF;
END;
$$ LANGUAGE plpgsql;
毕竟我想在表vote
中插入一个新行,其中:
_cafe = cafes._id
_song = songs._id
_user = users._id
有人可以帮帮我吗?
答案 0 :(得分:3)
我做了一些调整。
user
是reserved word,我使用usr
作为列名。votes.cafe
为integer
,而不是text
。
CREATE OR REPLACE FUNCTION testfunc(
_user_imei text
,_cafe_ip text
,_song_artist text
,_song_name text) RETURNS void AS
$func$
DECLARE
id_cafe integer;
id_user integer;
id_song integer;
BEGIN
-- user
SELECT INTO id_user id FROM users WHERE imei = _user_imei;
IF NOT FOUND THEN
INSERT INTO users (imei) VALUES (user_imei)
RETURNING id INTO id_user;
END IF;
-- cafe
SELECT INTO id_cafe id FROM cafes WHERE ip = _cafe_ip;
IF NOT FOUND THEN
INSERT INTO cafes (ip) VALUES (cafe_ip)
RETURNING id INTO id_cafe;
END IF;
-- song
SELECT INTO id_song id FROM songs
WHERE artist = _song_artist AND name = _song_name;
IF NOT FOUND THEN
INSERT INTO songs (artist, name) VALUES (_song_artist, _song_name)
RETURNING id INTO id_song;
END IF;
INSERT INTO votes (cafe, usr, song) -- What about column vote??
VALUES (id_cafe, id_user, id_song); -- Assuming cafe is type integer
END
$func$ LANGUAGE plpgsql;