Using Postgres.
I have a pricelists
CREATE TABLE pricelists(
id SERIAL PRIMARY KEY,
name TEXT,
parent_id INTEGER REFERENCES pricelists
);
and another table, prices, referencing it
CREATE TABLE prices(
pricelist_id INTEGER REFERENCES pricelists,
name TEXT,
value INTEGER NOT NULL,
PRIMARY KEY (pricelist_id, name)
);
- Parent pricelist
id=1may have 10 prices. - Pricelist
id=2as a child of parent1may have 5 prices which override parent1prices of the same price name. - Child Pricelist
id=3as as a child of pricelist2may have 2 price which override child2prices of the same price name.
Thus when I ask for child 3 prices, I want to get
- all prices of child
3and - those prices of his parent (child
2) that do not exists in child3and - all parent
1prices that do not exists until now.
The schema can be changed in order to be efficient.
Example:
If
SELECT pl.id AS id, pl.parent_id AS parent, p.name AS price_name, value
FROM pricelists pl
JOIN prices p ON pl.id = p.pricelist_id;
gives
| id | parent | price_name | value |
|----------|:-------------:|------------:|------------:|
| 1 | 1 | bb | 10 |
| 1 | 1 | cc | 10 |
| 2 | 1 | aa | 20 |
| 2 | 1 | bb | 20 |
| 3 | 2 | aa | 30 |
then I'm looking for a way of fetching pricelist_id = 3 prices that'd give me
| id | parent | price_name | value |
|----------|:-------------:|------------:|------------:|
| 1 | 1 | cc | 10 |
| 2 | 1 | bb | 20 |
| 3 | 2 | aa | 30 |