1
Considering these two tables in the database:
Product Table:
| id | nome |
|-----|-----------|
| aaa | Produto A |
| bbb | Produto B |
| ccc | Produto C |
Attributes Table:
| id_produto | atributo | valor |
|------------|----------|---------|
| aaa | cor | azul |
| aaa | tamanho | M |
| bbb | cor | preto |
| bbb | tamanho | P |
| ccc | cor | amarelo |
| ccc | tamanho | G |
and the following SQL query:
select
p.nome,
c.valor,
t.valor
from
Produto p,
Atributos c,
Atributos t
where
p.id = c.id_produto and
p.id = t.id_produto and
c.atributo = 'cor' and
t.atributo = 'tamanho'
Is there any way to make this select without duplicating the table attributes?
Edit #1
Upshot:
| nome | cor | Tamanho |
|-----------|---------|---------|
| Produto A | azul | M |
| Produto B | preto | P |
| Produto C | amarelo | G |
Note: I cannot change the table structure, the real database has several different attribute types (they are generated dynamically) and thousands of records.
You’re using letters on
primary_key
?– rbz
Is slowing down?
– gabrielfalieri
All data is received via integration, and yes, it can have letters in the key Primary. the point is not the database structure, but rather how select is done
– Pilati
I believe what you want is to transpose the result of the table
atributos
for each occurrence ofproduto
. Research onpivot
– Diego Rafael Souza
How would I get this result using pivot?
– Pilati
I posted as an answer based on your example model. Apply there in your real scenario and check if the molhora of performance is reflected. I believe so, because for every 'attribute' you wanted to include in the result you would have to generate a Cartesian product in the table
atributos
if you follow the current approach.– Diego Rafael Souza