tags:

views:

190

answers:

1

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
+3  A: 

I'd recommend retooling the way product colors are stored, turning it into something like this:

products:
productId | imgId | productName
1           1       rock
2           null    roll

productcolors:
productId | colorId
1           1
1           2

colors:
colorId   | colorName
1           copper
2           slate

images:
imgId | imgSrc
1       img1_0.png

productcolors above is a many-to-many join table.

This also assumes that you only have one image for each product, and leaves that table alone.

To get a list of products including their colors:

SELECT p.productId, p.productName, c.colorId, c.colorName, i.imgSrc
FROM products p
LEFT JOIN images i USING (imgId)
LEFT JOIN productcolors pc USING(productId)
LEFT JOIN color c USING(colorId)
R. Bemrose
Thank you! I guess I basically could do the same for the images.
Baversjo