我已经创建了一个查询以获取非销售产品。这里我们有两个主表,一个是产品表,第二个是order_product表。要获取非销售产品,我想从产品表中获取order_product表中不存在的那些产品。此查询在localhost上运行正常,但是当我在主服务器上执行此操作时需要更长的时间并且由于此超时发生。如何提高此查询的速度或优化我的查询。
SELECT p.date_added, p.model, p.status, p.quantity, ptc.category_id, pd.name AS product_name, cd.name AS category_name FROM (`product` p INNER JOIN `product_description` pd ON p.product_id= pd.product_id) INNER JOIN (`product_to_category` ptc INNER JOIN `category_description` cd ON ptc.category_id = cd.category_id) ON p.product_id = ptc.product_id
WHERE p.product_id NOT IN (SELECT product_id FROM `order_product`)
ORDER BY p.quantity DESC LIMIT 1,100
答案 0 :(得分:1)
以下是不使用not in
SELECT
p.date_added,
p.model,
p.status,
p.quantity,
ptc.category_id,
pd.name AS product_name,
cd.name AS category_name
FROM `product` p
INNER JOIN `product_description` pd ON p.product_id= pd.product_id
INNER JOIN `product_to_category` ptc ON p.product_id = ptc.product_id
INNER JOIN `category_description` cd ON ptc.category_id = cd.category_id
left join `order_product` op on op.product_id = p.product_id
WHERE
op.product_id is null
ORDER BY p.quantity DESC LIMIT 1,100
您需要确保对于所有连接条件,索引相应的列,并且需要以下2个索引来解析位置和顺序
alter table product add index quantity_idx(quantity);
alter table order_product add index product_id_idx(product_id);
您可以使用explain select ...
来检查查询运行状况。
答案 1 :(得分:0)
可能是IN语句需要时间来执行。 我在这里使用外部联接:
SELECT p.date_added, p.model, p.status, p.quantity, ptc.category_id, pd.name AS product_name, cd.name AS category_name FROM `product` p INNER JOIN `product_description` pd ON p.product_id= pd.product_id INNER JOIN `product_to_category` ptc INNER JOIN `category_description` cd ON ptc.category_id = cd.category_id ON p.product_id = ptc.product_id
LEFT OUTER JOIN `order_product` op ON p.product_id = op.product_id WHERE op.order_product_id IS NULL
ORDER BY p.quantity DESC LIMIT 1,100