优化 SQL 查询?

Optimizing SQL query?

我有一个查询,我想在其中 select 所有订购了特定 product_id(例如 12,13)的客户。我为此做了一个fiddle。有一个命令 table,其中包含 order_id 和 customer_id。 Order_detail table 有 order_id 和 product_id。这些是示例 table。原始 table 包含超过 30000 条记录。你能帮我优化查询或指导我这样做吗?

http://sqlfiddle.com/#!9/838da/3

select c.* from customer_detail c 
inner join orders o on o.customer_id = c.customer_id
inner join order_detail od on od.order_id = o.order_id
where od.product_id in (12,13);

我想这就是你要找的。

您可以使用下面的最终查询-

SELECT customer_id,first_name 
FROM customer_detail cd 
JOIN orders ors ON cd.customer_id=ors.customer_id 
JOIN order_detail od ON od.order_id=ors.order_id 
WHERE product_id IN (12,13); 

注意:应为以下字段编制索引 - customer_id 在订单中 TABLE order_id 和 product_id 在 order_detail TABLE