D
D
Dmitry Dobryshin2019-06-22 20:56:59
PostgreSQL
Dmitry Dobryshin, 2019-06-22 20:56:59

How to set the uniqueness of a field together with a field from another table?

The bottom line is this:
There is a type table:

types
------
id,
name,
prefix

Model table
models
--------
id,
name
type_id

And the product table:
items
------
id
model_id
number

The tables are related to each other - model and type by type_id, id, and products and models by model_id and id
The essence of the question is that it is necessary to ensure the uniqueness of the number field in items together with the prefix field in types.
That is, when creating a request:
SELECT
    a.id,
    to_char(c.prefix, 'FM0000') || '-' || to_char(a.number, 'FM0000000000') AS code
FROM
   items  AS a
   INNER JOIN models AS b ON a.model_id = b.id
   INNER JOIN types AS c ON b.type_id = c.id

the code field must be unique, while number and prefix can be repeated in their tables.
INDEX is not created for two or more tables.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rPman, 2019-06-23
@DimkaI

A universal way for any database and tricks that you come up with is to create a table with a field and an index in the format you need, and fill it with a trigger. If the index of this table fails, the change request of the subordinate tables will also fail, only that the error message will be 'unusual'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question