1
I have a table catalogo related to another table imagens.
Each record in catalogo has N images.
I need that in a SELECT with INNER JOIN imagens, only 3 images are returned for each table row catalogo.
I thought I’d settle the matter with something like this:
SELECT c.`cat_id` as id, c.`cat_nome_fantasia` as empresa, i.img_nome as imagem FROM `catalogo` c
LEFT JOIN (SELECT * FROM imagens WHERE fk_catalogo_id=**c.cat_id** LIMIT 3) i ON c.cat_id=i.fk_catalogo_id
But the column cat_id in the subquery (WHERE fk_catalogo_id=c.cat_id ) is not recognized.
Do you know if there’s any way to change that? Like making the column Global.
So I tried:
SELECT (**@valor_id:=** c.`cat_id`) as id, c.`cat_nome_fantasia` as empresa, i.img_nome as imagem FROM `catalogo` c
LEFT JOIN (SELECT * FROM imagens WHERE fk_catalogo_id=**@valor_id** LIMIT 3) i ON c.cat_id=i.fk_catalogo_id
But the @valor_id seems not to have been set as no records returned.
Finally I tried to set the variable:
SET @valor_id:=1;
SELECT (**@valor_id:=** c.`cat_id`) as id, c.`cat_nome_fantasia` as empresa, i.img_nome as imagem FROM `catalogo` c
LEFT JOIN (SELECT * FROM imagens WHERE fk_catalogo_id=**@valor_id** LIMIT 3) i ON c.cat_id=i.fk_catalogo_id
In this case almost worked, searched the images with LIMIT.
But, got stuck to manually set the @valor_id, ie, just search the images of the id set.
Does anyone have any idea how to solve?
At first
SELECThasc.cat_id as id. From there, you should use the alias (id) further on. Then it would be:... WHERE fk_catalogo_id=id LIMIT 3) i ON id=i.fk_catalogo_id– Rene Freak
Hi Rene, first thank you for the collaboration. I tried but still gives the error type "column (id) not found in the WHERE clause". I tried using alias (id) alone and with c.id. The field (id) is only not recognized in the SELECT WHERE. Outside the subquery it is usually recognized using or not the alias. Thank you
– Giovani Silva