Matthew Winter
Matthew Winter

Reputation: 65

MySQL - join same table twice

I have a table called 'booking'

> id     status 
  1      P 
  2      P

and another called 'call'

id    calldate    type   booking
1     01/01/2012  DEL    1
2     01/02/2012  COL    1
3     01/03/2012  DEL    2
4     31/12/2019  COL    999

I want to list each record in 'bookings' ONCE, showing associated records from 'call' as another column like this:

bookingId    deliverydate  collectiondate
1            01/01/2012    01/02/2012
2            01/03/2012    null

I've tried:

select `b`.`bookingid` AS `bookingid`,
       `del`.`calldate` AS `Delivery`,
       `col`.`calldate` AS `Collection`
from `booking` `b`
left join `call` `del` on `b`.`bookingid` = `del`.`booking`
left join `call` `col` on `b`.`bookingid` = `col`.`booking`
where ((`del`.`type` = 'DEL') OR (`col`.`type` = 'COL') and (`b`.`status` = 'P'));

but I get bookingid 1 listed 3 times. Can someone please fix my joins?

Upvotes: 0

Views: 1749

Answers (2)

fthiella
fthiella

Reputation: 49049

You don't need to join the same table twice, you could use this:

SELECT
  `call`.booking,
  max(case when type='DEL' then calldate end) as deliverydate,
  max(case when type='COL' then calldate end) as collectiondate
FROM
  booking inner join `call`
  on booking.id=`call`.booking
WHERE
  booking.status='P'
GROUP BY `call`.booking

Upvotes: 0

jmoerdyk
jmoerdyk

Reputation: 5521

I think you want to move your types into the join conditions:

select `b`.`bookingid` AS `bookingid`,
   `del`.`calldate` AS `Delivery`,
   `col`.`calldate` AS `Collection`
from `booking` `b`
left join `call` `del` on `b`.`bookingid` = `del`.`booking` AND `del`.`type` = 'DEL'
left join `call` `col` on `b`.`bookingid` = `col`.`booking` AND `col`.`type` = 'COL'
where `b`.`status` = 'P';

Upvotes: 3

Related Questions