优化mySQL LEFT JOIN

时间:2015-02-06 22:05:37

标签: mysql join

我有一张旅行表,其中已完成的旅行在trip.txnPNR中有一个交易ID。

我有一个driver_contacts表,它引用了trips.id。

我必须查明是否存在trip.txnPNR设置的行程,但是在driver_contacts.trip中没有带有该ID的行表示。

我使用此JOIN成功定位了这些行程,但显然它非常耗费内存。

SELECT
 trips.id,
 driver_contacts.trip
FROM trips
LEFT JOIN driver_contacts ON trips.id = driver_contacts.trip WHERE trips.`tripDropoff` > '2014-10-24 15:15:25'
AND driver_contacts.trip IS NULL
AND TRIM(trips.txnPNR) != ''

我的同事建议更快地改变

SELECT
 24hourTrips.id,
 driver_contacts_null.trip
FROM (SELECT id,txnPNR FROM trips WHERE trips.`tripDropoff` > now() - INTERVAL 1 DAY AND
TRIM(txnPNR) != '') AS 24hourTrips
LEFT JOIN (SELECT * FROM driver_contacts where driver_contacts.trip IS NULL) AS driver_contacts_null ON 24hourTrips.id = driver_contacts_null.trip

但该查询获取所有行程,无论他们是否在driver_contacts中有行。

对于id不在driver_contacts.trip中的所有行的行,什么是不太密集的查找?

1 个答案:

答案 0 :(得分:0)

找到解决方案!在一秒钟内返回,这样每个人都很开心。

SELECT
24hourTrips.id,
driver_contacts.trip
FROM (SELECT id,txnPNR FROM trips WHERE trips.`tripDropoff` > now() - INTERVAL 1 DAY AND
TRIM(txnPNR) != '') AS 24hourTrips
LEFT OUTER JOIN driver_contacts ON 24hourTrips.id = driver_contacts.trip WHERE driver_contacts.trip IS NULL AND TRIM(24hourTrips.txnPNR) != ''