views:

92

answers:

2

At the moment I have two tables, products and options.

Products contains

  1. id
  2. title
  3. description

Options contains

  1. id
  2. product_id
  3. sku
  4. title

Sample data may be:

Products
id: 1
title: 'test'
description: 'my description'

Options
id: 1
product_id: 1
sku: 1001
title: 'red'

id: 2
product_id: 1
sku: 1002
title: 'blue'

I need to display each item, with each different option. At the moment, I select the rows in products and iterate through them, and for each one select the appropriate rows from options. I then create an array, similar to:

[product_title] = 'test';  
[description]   = 'my description';  
[options][]     = 1, 1001, 'red';  
[options][]     = 2, 1002, 'blue';

Is there a better way to do this with just sql (I'm using codeigniter, and would ideally like to use the Active Record class)?

+4  A: 

Start with

SELECT * FROM products INNER JOIN options ON product.id = options.product_id

and work from there.

The example only works for products with at least one option available (which is required by your design, otherwise you have no place for the SKU). But if some products don't have any options at all, you want:

SELECT * FROM products LEFT JOIN options ON product.id = options.product_id

Finally, it's considered good practice to list the actual columns you want to get back instead of SELECT *.

Larry Lustig
+1 modern join syntax
KM
Thanks. However, is there a way to retrieve it as some kind of 2d table, where I have the product, and a 'column' containing the table of options?
Josh
@Josh. Not in standard SQL and not, to the best of my knowledge (which is *not* definitive) in MySQL. Some DBMSes allow multiple and nested results sets but it's very non-standard. Also, an ORM will probably support this assuming you correctly declare the relationship in the DM and the ORM — then you would access the option records through a collection property of the object representing a product record.
Larry Lustig
Ah, I'll have a look into that then. Thanks for the fantastic answer!
Josh
+1  A: 

You need to join products and options. Try this query:

select *
from products, options
where products.id = options.product_id
FrustratedWithFormsDesigner