0

「予約」というテーブルがあります

> id     status 
  1      P 
  2      P

もう1つは「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

「bookings」の各レコードを 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'));

しかし、bookingid 1 が 3 回リストされます。誰かが私の結合を修正してもらえますか?

4

2 に答える 2

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';
于 2012-12-18T23:50:03.403 に答える
0

同じテーブルに 2 回参加する必要はありません。これを使用できます。

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
于 2012-12-18T23:50:28.077 に答える