I'm using MySql and I need to do a specific query. I have 2 tables : Customer
and Booking
. Each customers can have many bookings. So I need to join theses tables but I want to display the nearest booking start date.
Here is my query :
SELECT b.number, b.start_date, c.*
FROM customer c LEFT JOIN booking b ON (c.id = b.id_customer)
GROUP BY c.id
So with my query I'll get all customers with random booking. What I need is to display the nearest (to the current date) booking start date with his number. Something like this :
SELECT nearest booking number, nearest start date, c.*
FROM customer c LEFT JOIN booking b ON (c.id = b.id_customer)
GROUP BY c.id
It is possible to do that ?
CREATE TABLE customer (
id int,
name varchar(80)
);
CREATE TABLE booking (
id int,
number varchar(80),
customer_id int,
start_date datetime
);
INSERT INTO booking (id, number, customer_id, start_date) VALUES
(1 , 'booking-1', 1, '2019-11-05 21:45:00'),
(2 , 'booking-2', 1, '2019-11-05 18:30:00'),
(3 , 'booking-3', 2, '2019-09-27 21:45:00'),
(4 , 'booking-4', 1, '2019-09-27 21:45:00'),
(5 , 'booking-5', 3, '2019-09-27 21:45:00');
INSERT INTO customer (id, name) VALUES
(1 , 'Paul'),
(2 , 'John'),
(3 , 'Morgan'),
(4 , 'Jane'),
(5 , 'Mike');
See : http://sqlfiddle.com/#!9/df0455/1
I tried using this:
SELECT b.number, b.start_date
FROM customer c LEFT JOIN booking b ON (c.id = b.customer_id)
INNER JOIN (
SELECT id, MIN(ABS(DATEDIFF(NOW(), start_date)))
FROM booking
GROUP BY id
) nearest ON (b.id = nearest.id)