MySQL-连接同一个表两次
我有一张叫“预订”的桌子MySQL-连接同一个表两次,mysql,sql,join,Mysql,Sql,Join,我有一张叫“预订”的桌子 > id status 1 P 2 P 还有一个叫“呼叫” 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”中列出每条记录一次,将“call”中的相关记录显示为
> id status
1 P
2 P
还有一个叫“呼叫”
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”中列出每条记录一次,将“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'));
但是我的预订ID被列了三次。有人可以修复我的联接吗?我想您希望将类型移动到联接条件中:
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';
我认为您希望将类型移动到联接条件中:
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';
您不需要两次加入同一个表,可以使用以下方法:
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
您不需要两次加入同一个表,可以使用以下方法:
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
完美地工作-我从来都不知道你能用连接做到这一点!谢谢你的帮助:)工作得很好-我从来都不知道你能用连接做到这一点!谢谢你的帮助:)