I have the following tables in MySQL
`orders` (
`orderID` int(10) unsigned NOT NULL auto_increment,
`agentID` int(10) unsigned NOT NULL,
`order_date` datetime NOT NULL,
`senderID` int(10) unsigned NOT NULL,
`receiverID` int(10) unsigned NOT NULL,
PRIMARY KEY (`orderID`)
)
`order_details` (
`order_details_id` int(10) unsigned NOT NULL auto_increment,
`orderID` int(10) unsigned NOT NULL,
`packageID` int(10) unsigned NOT NULL,
PRIMARY KEY (`order_details_id`),
KEY `fk_orderID` (`orderID`)
)
`order_status` (
`status_id` int(10) unsigned NOT NULL auto_increment,
`order_details_id` int(10) unsigned NOT NULL,
`descrID` int(10) unsigned NOT NULL,
`date_time` datetime NOT NULL,
PRIMARY KEY (`status_id`),
KEY `theDate` (`date_time`),
KEY `stat` (`descrID`,`order_details_id`,`date_time`)
)
`order_statuses` (
`descrID` int(10) unsigned NOT NULL auto_increment,
`descr` varchar(255) collate utf8_bin NOT NULL,
`public` smallint(6) NOT NULL COMMENT '1 or 0',
`leg` tinyint(4) NOT NULL COMMENT 'carrier code',
PRIMARY KEY (`statusID`)
)
The third and fourth tables are used to keep track of all the stages the orders go through. The flow is as follows: an order is placed at an agent of the company, the agent gives the order to a carrier, the carrier transfers the order to a hub owned by the company, another carrier picks it up and then hopefully delivers it. 2 questions;
First, any comments on the design?
Second, I need to run a query that will give me the all the orders based on the specific LATEST status per carrier. Right now the query that I am using is taking about 1.5 seconds to complete and I only have one row in the tables.
select odd.order_details_id
from order_details odd, orders od
where odd.orderID = od.orderID and (
select oas.statusID
from order_status oas, order_statuses oss
where oas.descrID = oss.descrID and oss.leg=1 and odd.order_details_id =oas.order_details_id
order by oas.date_time desc limit 1)=2
Is there a way to optimize this? Thanks