Hello marcos_Brz!
Have you considered using a view? It's probably better suited to your example than a trigger.
Using your example:
Code:
--Create the Tables:
create table books
(bookid int, title varchar(50), price decimal(14,2), idPublisher int);
create table publisher
(Idpublisher int , name varchar(50), city varchar(50));
-- Popluate Tables:
insert into books values(501, 'Zombie Survival Guide', 5.99, 5);
insert into books values(502, 'World War Z', 6.99, 5);
insert into books values(102, 'The Return of Sherlock Holmes', 3.99, 2);
insert into books values(102, 'The Hound of the Baskervilles', 3.50, 2);
insert into books values(102, 'The Adventures of Sherlock Holmes', 3.99, 2):
insert into publisher values(5, 'Random House', 'New York');
insert into publisher values(2, 'Penguin', 'London');
Compile the view
Code:
create view publisher_books as
select a.Idpublisher, a.name, a.city, count(1) total_books
from publisher a
inner join books b
on a.idPublisher=b.idPublisher
group by a.Idpublisher, a.name, a.city;
Select from the view
Code:
postgres=# select * from publisher_books;
idpublisher | name | city | total_books
-------------+--------------+----------+-------------
2 | Penguin | London | 3
5 | Random House | New York | 2
(2 rows)