[eluser]ggoforth[/eluser]
[quote author="slowgary" date="1243414700"]Or at least I
think I need JOIN help. I have a table of products, and a table of product images, each with a corresponding prod_id field.
How can I select * from products, and also tack on 1 image for each product?
In other words, when looking at an individual product in detail view, I'll select * for that product, plus select * images for that product. My problem is when I want to list all products in a category. I can select * from products, but I don't want to run an additional query for each product (could be many) just to get an image. I don't need to get all the images for a product, just one.
I've tried many JOIN queries (which I'm terrible at) as well as a few other things. My query for getting a product list from a given category is currently pretty ugly:
Code:
$this->db->query("
SELECT *
FROM `shop_products`
WHERE prod_id IN (
SELECT `prod_id`
FROM `shop_product_categories`
WHERE `cat_id` = (
SELECT `cat_id`
FROM `shop_categories`
WHERE `cat_name` = '$category_name' LIMIT 1
)
)
");
I just need to add a single image from the shop_product_images table for each row of this query. What the deuce?[/quote]
Not sure I quite understand, but if your table set up is like this:
shop_products <- has all your info
shop_product_images <- has your image info and links via product_id
Your query would look like:
Code:
SELECT shop_products.*,shop_product_images.field_you_need FROM shop_products JOIN shop_product_images ON shop_products.product_id = shop_product_images.product_id WHERE shop_products.product_id = $some_id
Or with active record:
Code:
$this->db->select('shop_products.*')->select('shop_product_images.field_you_need')->from('shop_products')->join('shop_product_images','shop_products.product_id = shop_product_images.product_id')->where('shop_products.product_id',$product_id)->get();
Hope that helps.
Greg