views:

46

answers:

2

Thankfully, I haven't had to work with particularly complex SQL queries before. Here's my goal.

I have the table hams, which I would like to cross-join with the table eggs - that is, get all ham-egg combinations... to an extent.

The eggs table also has an attribute how_cooked, which is defined as ENUM('over-easy','scrambled','poached'). I would like a resultset listing every possible combination of ham and egg-cooking method, along with a sample egg cooked that way. (I don't care which egg in particular.)

So if 3 hams with id of 1, 2, and 3, and 3 eggs of each cooking method, my resultset should look something like this:

+---------+-----------------+---------+
| hams.id | eggs.how_cooked | eggs.id |
+---------+-----------------+---------+
| 1       | over-easy       | 1       |
| 1       | scrambled       | 4       |
| 1       | poached         | 7       |
| 2       | over-easy       | 1       |
| 2       | scrambled       | 4       |
| 2       | poached         | 7       |
| 3       | over-easy       | 1       |
| 3       | scrambled       | 4       |
| 3       | poached         | 7       |
+---------+-----------------+---------+

I'm sure I could hack together some solution with loads of subqueries here and there, but is there any elegant way to do this is MySQL?

+2  A: 

Through a bit of thinking real hard and Googling, I may have found a good solution:

SELECT * FROM hams, eggs GROUP BY hams.id, eggs.how_cooked

It seems to work. Is it really that easy?

Matchu
It works, yes, but only because you `don't care which egg in particular`. SQL behavior for selecting columns not in a `GROUP BY` isn't well-defined. However, in my experience, it always returns a valid value. Also, this'll only work as long as `eggs` contains at least one occurrence of each value in the enum (of course, it looks like this is a pretty safe assumption).
cmptrgeekken
Good - I'm glad to know that there are, in fact, well-defined gotchas, since if there weren't any obvious ones, I'm sure obscure ones would show up. Thanks!
Matchu
and mysql is afaik the only database that will allow you to do it this way
ysth
Which I believe is wrong, as it tempts you to believe the extraneous data actually relates to the aggregate data specifically.
RedFilter
Your query does not seem to work in MySQL 5.5
Buckwad
A: 
SELECT hams.id, eggs.how_cooked, eggs.id
FROM hams
  CROSS JOIN eggs

This does the trick. CROSS JOIN is synonymous with , but has a higher precedence in MySQL .

MySQL 5.0 Reference - JOIN syntax

Buckwad