Question

I currently have two tables:

Table 1 has a unique ID and a count.

Table 2 has some data columns and one column where the value of the unique ID of Table 1 is inside.

When I insert a row of data in Table 2, the the count for the row with the referenced unique id in Table 1 should be incremented.
Hope I made myself clear. I am very new to PostgreSQL and SQL in general, so I would appreciate any help how to do that. =)

Was it helpful?

Solution

You could achieve that with triggers.
Be sure to cover all kinds of write access appropriately if you do. INSERT, UPDATE, DELETE.
Also be aware that TRUNCATE on Table 2 or manual edits in Table 1 could break data integrity.

I suggest you consider a VIEW instead to return aggregated results that are automatically up to date. Like:

CREATE VIEW tbl1_plus_ct AS
SELECT t1.*, t2.ct
FROM   tbl1 t1
LEFT JOIN  (
   SELECT tbl1_id, count(*) AS ct
   FROM   tbl2
   GROUP  BY 1
   ) t2 USING (tbl1_id)

If you use a LEFT JOIN, all rows of tbl1 are included, even if there is no reference in tbl2. With a regular JOIN, those rows would be omitted from the VIEW.

For all or much of the table, it is fastest to aggregate tbl2 first in a subquery, then join to tbl1 - like demonstrated above.

Instead of creating a view, you could also just use the query directly, and if you only fetch a single row, or only few, this alternative form would perform better:

SELECT t1.*, count(t2.tbl1_id) AS ct
FROM   tbl1 t1
LEFT   JOIN  tbl2 t2 USING (tbl1_id)
WHERE  t1.tbl1_id = 123  -- for example
GROUP  BY t1.tbl1_id     -- being the primary key of tbl1!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top