Considering the following structure:
CREATE TABLE artigos (
referencia VARCHAR(1),
quantidade INTEGER,
preco NUMERIC(15, 2)
);
INSERT INTO artigos(referencia, quantidade, preco)
VALUES ('X', 2, 1.0),
('Y', 5, 2.0),
('A', 1, 5.0),
('B', 7, 3.0),
('C', 4, 4.0);
CREATE TABLE associadas(
referencia VARCHAR(1),
associada VARCHAR(1)
);
INSERT INTO associadas(referencia, associada)
VALUES ('X', 'A'),
('X', 'B'),
('Y', 'C');
To query
to get the result you want would be:
SELECT x.referencia,
x.quantidade,
x.preco
FROM (
SELECT art.referencia AS aux,
art.referencia,
art.quantidade,
art.preco
FROM artigos art
WHERE EXISTS(SELECT 1
FROM associadas ass
WHERE ass.referencia = art.referencia)
UNION
SELECT ass.referencia AS aux,
art.referencia,
art.quantidade,
art.preco
FROM artigos art
INNER JOIN associadas ass ON ass.associada = art.referencia
) x
ORDER BY x.aux,
CASE x.aux
WHEN x.referencia THEN 0
ELSE 1
END;
In the query
above we would link the records to those that are hierarchically larger and we would sort by that relation.
Or by simplifying:
SELECT art.referencia,
art.quantidade,
art.preco
FROM artigos art
LEFT JOIN associadas ass ON ass.associada = art.referencia
ORDER BY COALESCE(ass.referencia, art.referencia),
CASE
WHEN ass.referencia IS NULL THEN 0
ELSE 1
END
The result would be:
| referencia | quantidade | preco |
| ---------- | ---------- | ----- |
| X | 2 | 1 |
| A | 1 | 5 |
| B | 7 | 3 |
| Y | 5 | 2 |
| C | 4 | 4 |
You can check the result in DB Fiddle for the first example or for the second example.
That column of yours
ReferenciasAssociadas
is a text field? If yes the table design is already bad– Sorack
This is just an example and it’s not the real case where I’m going to apply this, the actual table design isn’t like this.
– Diogo Fernandes
Only this influences the answer. You have a column only with the keys or you have another table that relates the other codes?
– Sorack
Detailing, I have a table articles where you have quantity and price information. I have a table of associated references where for example there are 2 lines (reference A and B). The foreign key between these two tables is the reference.
– Diogo Fernandes
Beauty, it makes the answer easier
– Sorack