Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql join problem

Tags:

join

mysql

table a
-------------------------------------------------
id   name     wishlist1    wishlist2     wishlist3

1    john      1              2            3
2    paul      4              5


table b
--------------------------------------------------
id    goods

1     car
2     aircraft
3     bicycle
4     motorbike
5     ipad


result i want to get
---------------------------------------------------
john    car        aircraft    bicycle
paul    motorbike  ipad

how could i get this result? (in mysql)

like image 331
soredive Avatar asked Jul 22 '11 07:07

soredive


1 Answers

This outputs up to 3 wishes (with nulls in wish columns when they don't have a wish)

select
  name,
  g1.goods as wish1,
  g2.goods as wish2,
  g3.goods as wish3
from tablea a
left join tableb g1.id on g1.wishlist1
left join tableb g2.id on g1.wishlist2
left join tableb g3.id on g1.wishlist3

This might be better though, and it's neater, if you don't mind a comma-delimited list of wishes:

select
  name,
  group_concat(goods) as wishes
from tablea a
left join tableb b on b.id in (a.wishlist1, a.wishlist2, a.wishlist3)
group by name;

which will output:

name  |  wishes
------|----------------------
john  |  car,aircraft,bicycle
paul  |  motorbike,ipad
like image 142
Bohemian Avatar answered Sep 24 '22 01:09

Bohemian