I'm trying to avoid using queries in while loops. Therefore I've come to the conclusion that I should use a cross join. Take this example:
SELECT * FROM products
CROSS JOIN images USING (imgId)
CROSS JOIN productcolors ON colorsId = colorId
WHERE productId = 1
should return two rows (table structure below):
imgId | productId | colorId | imgSrc | colorName
1 1 1 img1_0.png copper
imgId | productId | colorId | imgSrc | colorName
1 1 1 img1_0.png slate
and when productId = 2 should return one row:
imgId | productId | colorId | imgSrc | colorName
null 2 -1 null null
The images table contains multiple records with the same imgId, the same applys for productcolors where several colorIds could / will have the same value. There could also be no records in the images table (if imgId for example = -1 in the products table). That would mean that a product has no colors. Now, when I make this query and the images table or productcolors table contains no record for the imgId or colorId the query will return no result at all. I would like the fields in the row to contain null values instead of not returning anything, behaving like a Left outer join and cross join together.
Maybe I should have queries in my whileloop instead? Is there maybe any other way to approach this problem?
EDIT: My tables
products:
productId | colorsId | imgId
1 1 1
2 -1 -1 //product 2 has no images nor colors
productcolors:
colorId | colorName
1 copper
1 slate
images:
imgId | imgSrc
1 img1_0.png