Hello im trying to create a stock database for cars having 2 tables, carros and faturas, soo carros is the name of the car(veiculo) and how many cars i have in stock(quantidade) and how many cars i sold(vendidos), and the table faturas has the id and the car name(veiculo) the rest doesnt matter of my objective. My objective is after i insert on table faturas the car name(veiculo) it goes to the carros table and it adds +1 to the vendidos of that car, but for now it is updating all my vendidos row. Here it goes my code and i hope you can help me, Thanks.
CREATE TABLE carros (
veiculo VARCHAR(10) not null,
quantidade INTEGER not null,
vendidos INTEGER,
PRIMARY KEY (veiculo));
CREATE TABLE faturas (
id serial not null,
veiculo VARCHAR(10) NOT NULL,
matricula VARCHAR(10) NOT NULL,
nome CHAR(30) NOT NULL,
contacto VARCHAR(15) NOT NULL,
valor INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (veiculo) REFERENCES carros(veiculo));
CREATE OR REPLACE FUNCTION public.stockupdate()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
begin
IF EXISTS(select c.veiculo from carros c, faturas f where c.veiculo = f.veiculo limit 1) THEN
UPDATE carros SET vendidos = vendidos + 1 from faturas where carros.veiculo = faturas.veiculo;
end if;
return new;
end;
$function$
;
CREATE OR REPLACE FUNCTION public.stockupdate()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
begin
IF EXISTS(select c.veiculo from carros c, faturas f where c.veiculo = f.veiculo limit 1) THEN
UPDATE carros SET vendidos = vendidos + 1 from faturas where carros.veiculo = faturas.veiculo;
end if;
return new;
end;
$function$
;
create trigger stockupdatetrigger
before insert
on faturas
for each row
execute procedure stockupdate();
INSERT INTO carros
(veiculo, quantidade, vendidos)
VALUES('Opel', 10, 0);
INSERT INTO carros
(veiculo, quantidade, vendidos)
VALUES('Fiat', 10, 0);
INSERT INTO public.faturas
(veiculo, matricula, nome, contacto, valor)
VALUES('Opel', 'ABC 123', 'Ruben', '226-255243', 15000);
CREATE TABLE faturas (
id serial not null,
veiculo VARCHAR(10) NOT NULL,
matricula VARCHAR(10) NOT NULL,
nome CHAR(30) NOT NULL,
contacto VARCHAR(15) NOT NULL,
valor INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (veiculo) REFERENCES carros(veiculo)
);
CREATE OR REPLACE FUNCTION public.stockupdate()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
begin
IF EXISTS(select c.veiculo from carros c, faturas f where c.veiculo = f.veiculo limit 1) THEN
UPDATE carros SET vendidos = vendidos + 1 from faturas where carros.veiculo = faturas.veiculo;
end if;
return new;
end;
$function$
;
create trigger stockupdatetrigger
before insert
on faturas
for each row
execute procedure stockupdate();
INSERT INTO carros
(veiculo, quantidade, vendidos)
VALUES('Opel', 10, 0);
INSERT INTO carros
(veiculo, quantidade, vendidos)
VALUES('Fiat', 10, 0);
INSERT INTO public.faturas
(veiculo, matricula, nome, contacto, valor)
VALUES('Opel', 'ABC 123', 'Ruben', '226-255243', 15000);