0

I have a mysql table for bookings

Bookingid  Customer

  1         Steve
  2         John

and another table for passengers

Bookingid  Passenger

  1        Steve
  1        Gary
  1        Tom
  2        John
  2        Chris
  2        Thomas

What is the best query to get bookingid from the first table and passengers from the second table, in a single row ?

Bookingid  Passenger1 Passenger2 Passenger3
  1         Steve       Gary      Tom
  2         John        Chris     Thomas
krish211
  • 3
  • 2

1 Answers1

0

You can´t do this without a PIVOT TABLE Wich in most cases has fixed numbers of columns to rows.

This one has a procedure to do it automatticaly http://www.artfulsoftware.com/infotree/qrytip.php?id=523

But you have a function on MySql wich will give you something to work with. You will not see the Passenger1..PassengerN you will see a result like this:

1 Steve, Gary, Tom
2 John, Chris, Thomas

If that is good enough to you this is your query:

select passengers.Bookingid, group_concat(bookings.Customer)
  from bookings inner join passengers on ( bookings.Bookingid = passengers.Bookingid )
group by passengers.Bookingid 
Community
  • 1
  • 1
Jorge Campos
  • 22,647
  • 7
  • 56
  • 87