开发者

MySQL query involving cross join, uniqueness, etc

开发者 https://www.devze.com 2022-12-19 08:42 出处:网络
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-eg

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?


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消