Reputation: 305
I have three tables:
Table1 tipo_producto
id_tipo_producto nombre
1 Teléfono
2 Pendrive
3 Cargador
Table2 caracteristicas
id_caracteristicas nombre
1 Memoria
2 Camara
Table3 caracteristicas_tipo_producto
id_tipo_producto id_tipo_caracteristica
1 1
1 2
2 1
I want like result query like this:
id_tipo_producto nombre caracteristica
1 Teléfono Memoria|Camara
2 Pendrive Memoria
3 Cargador Null or Empty
I have this query but I haven't "Cargador" in the result:
SELECT tp.id_tipo_producto, tp.nombre, GROUP_CONCAT(c.nombre ORDER BY c.nombre DESC SEPARATOR '|') AS caracteristicas
FROM caracteristica c
INNER JOIN caracteristicas_tipo_producto ctp ON ctp.id_caracteristica = c.id_caracteristica
INNER JOIN tipo_producto tp ON ctp.id_tipo_producto = tp.id_tipo_producto
GROUP BY ctp.id_tipo_producto
Upvotes: 2
Views: 44
Reputation: 101
SELECT
tp.id_tipo_producto,
tp.nombre,
GROUP_CONCAT(c.nombre ORDER BY c.nombre DESC SEPARATOR '|') AS caracteristicas
FROM caracteristica c
INNER JOIN caracteristicas_tipo_producto ctp
ON c.caracteristicas = ctp.id_caracteristica
INNER JOIN tipo_producto tp
ON tp.id_tipo_producto = ctp.id_tipo_producto
GROUP BY ctp.id_tipo_producto
I'm surprised that your original even went through without error, because you misspelled the group_concat alias in the join clause. Also, try to follow a simple rule when joining tables> Although most newer versions won't blow up because of this, always put the table_whose_columns_are_first_mentioned as first and the joining table second (If you don't, you will be the one on the receiving end of confusing queries soon enough)
Let us know if the query worked
Upvotes: 1
Reputation: 37473
Use left join instead of inner join
SELECT tp.id_tipo_producto, tp.nombre, GROUP_CONCAT(c.nombre ORDER BY c.nombre DESC SEPARATOR '|') AS caracteristicas
FROM tipo_producto tp left JOIN caracteristicas_tipo_producto ctp
on ctp.id_tipo_producto = tp.id_tipo_producto
left join caracteristica c ON ctp.id_caracteristica = c.id_caracteristica
GROUP BY ctp.id_tipo_producto,tp.nombre
Upvotes: 2