MySQL - 连接两次相同的表

时间:2012-12-18 23:43:53

标签: mysql sql join

我有一张名为'预订'的表

> id     status 
  1      P 
  2      P

和另一个名为'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

我想列出'预订'ONCE中的每条记录,将'call'中的相关记录显示为另一列,如下所示:

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

我试过了:

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'));

但我预订了1次列出3次。有人可以修理我的连接吗?

2 个答案:

答案 0 :(得分:3)

我认为您希望将类型移动到连接条件中:

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';

答案 1 :(得分:0)

您不需要两次加入同一个表,您可以使用它:

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