Mr.SH Mr.SH - 2 months ago 5
MySQL Question

mysql join 4 tables with last multiple group by and where class

I have database for delivery of items to customers. for this i have 4 tables, delivery_logs, delivery,driver,customer

(we have delivery log table cause some time one delivery have many entries like not delivered & other driver take delivery etc)

delivery_log

id delivery_id driver_id message date_added
1 1 1 OK 2016-09-13 17:38:15
2 2 2 OK 2016-09-13 17:35:18
3 1 1 Not OK 2016-09-13 17:33:10
4 1 3 OK 2016-09-13 17:32:13
5 2 4 waiting 2016-09-13 17:20:11


delivery
delivery_id customer_id name status
1 1 delivery 1 done
2 1 delivery 2 done
3 2 delivery 3 done


driver
driver_id name
1 driver1
2 driver2
3 driver3

customer
customer_id first_name last_name
1 name1 other name1
2 name2 other name2
3 name3 other name3
4 name3 other name4


now i want to have query of


last 1 record (order by date_added) from delivery_log

for each delivery by each driver

where delivery= done


and i want to have bellow fields

delivery_log.delivery_id delivery_log.driver_id delivery_log.message date_added
delivery.name driver.name
customer.first_name customer.last_name


i have tried many inner join and join options but nothing seems to be working, some time it did't take last record & some time it mix (wrong) the delivery or driver name.

Thanks for all help.

Answer

You can use NOT EXISTS() and JOIN :

SELECT 
    dl.*,
    del.name,
    dr.name,
    c.first_name,
    c.last_name
FROM delivery_log dl
JOIN delivery del 
 ON(dl.delivery_id = del.delivery_id)
JOIN driver dr 
 ON(dr.driver_id = dl.driver_id)
JOIN customer c 
 ON(del.customer_id = c.customer_id)
WHERE del.status IN('DONE','OK')
  AND NOT EXISTS(SELECT 1 FROM delivery_log s
                 WHERE s.delivery_id = dl.delivery_id
                   AND s.driver_id = dl.driver_id
                   AND s.date_added > dl.date_added)