I am trying to create a mySql query to return a list of orders where they do not have a rate assigned to them. Currently I have:
SELECT * FROM Order
RIGHT JOIN Region ON Region.RegionID = Order.RegionID
LEFT JOIN RateSet ON RateSet.OrderID = Order.OrderID
LEFT JOIN Rate ON Rate.SalesID = RateSet.RateSetID
WHERE Rate.RateID IS NULL
The above query seems to achieve this however I want to take it one step further and only return orders where all orders in the region do not have a rate.
Greatly appreciate any help
Unusual situation – and I’m not at all sure that I understand why you have a RIGHT JOIN in amongst the LEFT JOIN conditions; it is the sort of thing that short-circuits my brain.
You have 4 tables:
We can guess that for table Xyz, the XyzID column is the primary key of the table. We can guess that a PqrID column in the table references table Pqr (except for SalesID, which does not have a corresponding table Sales – but it does seem to be a foreign key for joining Rate and RateSet (a puzzling inconsistency in the schema).
It would have been helpful to provide this information in the question. You might have got an answer quicker that way, too.
A given order seems to have one (possibly several) rate sets associated with it. Given the name, it appears that a given rate set can have a number of rates associated with it, including zero. It is not clear whether an order can be created without any associated rate sets, so we’ll take the conservative view that it can happen.
I don’t think that we need to select from Region; the RegionID in the orders table is sufficient identification of the region. The following query lists the order information for each Order where there is either no information in the RateSet table or no information in the Rate table for the RateSet.
Now, which regions have one or more orders, but not one of the orders for that region have a rate?
The sub-select lists the RegionID values of orders that have a rate assigned – using inner joins means that only rows with a rate will be selected. The regions not in that list are the only ones that are a candidate for ‘regions where none of the orders have a rate’. So we join that table with the previous query:
The schema structure is sufficiently unusual that I’m not sure about this – but it looks right.