I need help writing a query to display hotel id, hotel name and hotel type of
hotels which have not taken any orders in the month of 'MAY 19'. Sort the result based on hotel id in ascending order.
Assume we have two table hotel_details and orders.
I have tried the following code
select hotel_id,hotel_name,hotel_type from hotel_details
natural join orders
where order_id is null and monthname(order_date)="May"
group by(hotel_id);
Best Answer
You where on the right track;
natural joins are horrible because a) if there is no table structure, you can't read what they say (hence I'm guessing as the join critiera) b) people change the table structure in the future, and then the query is different.
A
left join
is required to match hotels where there is no orders. Yourwhere order_id is null
could never be true on the same row asmonthname(order_date)="May"
(iforder_id
is null, thenorder_date
must be also).As a
left join
criteria however, if there is no match, theorder
side of the result set is empty. Because of this properties we apply the month criteria here.Grouping by
hotel_id
was correct.Finally using
having
is a criteria based after the aggregation. AsNULL
isn't counted, the total count for the month must be 0.