I'd like to automatically update a database column with an aggregate of another column. There are three tables involved:
T_RIDER
RIDER_ID
TMP_PONYLIST
...
T_RIDER_PONY
RIDER_ID
PONY_ID
T_PONY
PONY_ID
PONY_NAME
...
T_RIDER
and T_PONY
have an n:m relationship via T_RIDER_PONY
.
T_RIDER
and T_PONY
have some more columns but only TMP_PONYLIST
and PONY_NAME
are relevant here.
TMP_PONYLIST
is a semicolon spararated list of PONY_NAMES
, imagine something like "Twisty Tail;Candy Cane;Lucky Leaf"
.
I'd like to keep this field up to date no matter what happens to T_RIDER_PONY
or T_PONY
.
My first idea was to have triggers on T_RIDER_PONY
and T_PONY
.
The problem is that it seems to be impossible to read T_RIDER_PONY
within the trigger, I always get ORA-04091
. I found some hints about working with three triggers and package variables, but this sounds way too complicated.
Maybe you think I'd better change the schema or get rid of TMP_PONYLIST
completely.
These are options but not the topic of this question.
For the moment I'm only interested in answers that don't require any change to my applications (no application works with the tables directly, only views, so trickery with views is allowed).
So, how can I keep TMP_PONYLIST
up to date automatically?
How to concatenate the string is an interesting subproblem I also have not yet found an elegant solution for.
I'm using Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi.
UPDATE
I like the idea of using a materialized view. What I have is:
CREATE MATERIALIZED VIEW
V_TMP_PONYLIST
BUILD IMMEDIATE
REFRESH COMPLETE ON COMMIT
AS SELECT
R.RIDER_ID, string_agg(P.PONY_NAME) AS TMP_PONYLIST
FROM
T_PONY P, T_RIDER R, T_RIDER_PONY RP
WHERE
P.PLOTGROUP_ID=RP.PLOTGROUP_ID AND
R.QUEUE_ID=RP.QUEUE_ID
GROUP BY R.RIDER_ID;
string_agg
is not shown because it is long and the I think it is not relevant.
It won't compile with ON COMMIT
, I get ORA-12054
.
As I understand the documentation aggregates are only forbidden with
REFRESH FAST
, so what's the problem here?
UPDATE Vincents and Tonys answers were different but both helpful. I accepted Tonys but be sure to read Vincents answer also.