阅读订单的查询非常缓慢。我尝试了很多东西,但无法获得更快的查询。下面是查询和数据库表。当然,所有重要的字段都有一个索引。我注意到按功能删除组会加快它的速度,但对查询进行分组很重要。
有更好的方式获得订单吗?提前谢谢。
SELECT
orders.id AS orderId, orders.delivery_from, orders.delivery_to,
orders_products.product_id, orders_products.color_id, ,orders_products.size_id,
sum(orders_products.quantity) as quantity,
customers.id AS customerId, customers.name AS customerName,
products.name
FROM orders
INNER JOIN orders_products ON orders_products.order_id=orders.id
INNER JOIN customers ON customers.id=orders.customer_id
INNER JOIN products ON orders_products.product_id=products.id
LEFT JOIN orders_product_data ON orders_product_data.order_id=orders.id AND orders_product_data.product_id=orders_product.product_id AND orders_product_data.color_id=orders_product.color_id
WHERE orders.status='0' AND
(orders.delivery_from<='2014-05-05' AND orders.delivery_to>='2014-05-05') AND
((orders_products_data.delivery_from<='2014-05-05' || orders_products_data.delivery_to=0) AND (orders_products_data.delivery_from>='2014-05-05' || orders_products_data.delivery_to=0))
GROUP BY customer_id, product_id, color_id, size_id
客户
CREATE TABLE IF NOT EXISTS `customers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(90) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
);
产品
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
);
订单
CREATE TABLE IF NOT EXISTS `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`customer_id` int(11) NOT NULL,
`delivery_from` date NOT NULL,
`delivery_to` date NOT NULL,
`status` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
订单产品
CREATE TABLE IF NOT EXISTS `orders_products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL DEFAULT '0',
`product_id` int(11) NOT NULL DEFAULT '0',
`color_id` int(11) NOT NULL DEFAULT '0',
`size_id` int(11) NOT NULL DEFAULT '0',
`quantity` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
颜色数据。下面的表格存储了order_id,product_id和color_id组合的交付信息,因为不同颜色的产品交付可能会发生变化。
CREATE TABLE IF NOT EXISTS `orders_products_data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL DEFAULT '0',
`product_id` int(11) NOT NULL DEFAULT '0',
`color_id` int(11) NOT NULL DEFAULT '0',
`delivery_from` date NOT NULL,
`delivery_to` date NOT NULL,
PRIMARY KEY (`id`)
);
解释查询
答案 0 :(得分:1)
您已经提到过您拥有所有重要字段的索引。
仅为您的信息 - 应根据访问路径而不是重要字段准备索引。
在订单,orders_product_data和添加以下索引后,在'...'和'...'之间替换delivery_from后检查:
在订单(status
,delivery_from,delivery_to)上创建索引idx_orders_status_delivery_from_to;