MySQL merge

Soldato
Joined
24 Nov 2002
Posts
16,378
Location
38.744281°N 104.846806°W
I have two tables in mysql that I'd like to easily link about a shared field (uid).

One table has 20 rows (and unique uid), the other has multiple rows referring to the single uid.

e.g.

Code:
food table:
type                uid
vegetable         1
alcohol             2
meat                3

item table:
item           uid
wine           2
beer           2
chicken       3

to:

Code:
end table:

item table:
item           type
wine           alcohol
beer           alcohol
chicken       meat


I was about to link the tables using php but wondered if there was an easier way?
 
SQL was designed to do that, this should work :

Code:
select item.item, food.type from item inner join food on item.uid = food.uid;

a conceptually simpler (to some people) method is the cross-join :

Code:
select item.item, food.type from item, food where item.uid = food.uid;

same result, but a cross-join is less efficient than an inner join (but you'd never notice the difference with less than 100 rows in each table). You might want to use an outer join instead, which would give the type numbers if they dont exist in the food table, whereas an inner join would not output them at all if they do not exist in the food table.
 
Last edited:
I knew it was simple!

Cheers... I did it in phpmyadmin (cross join > output > new table > input) much quicker.
 
Last edited:
Back
Top Bottom