我对MySQL很新,现在我尝试进行以下选择:
SELECT
a.qtd,
a.value
FROM
order_products a,
products b,
orders c
WHERE
b.id = a.product_id
and a.order_id = c.id
and c.status = '2'
and c.seller_id = '$result->seller_id'
and exists(select id from dealer_products p where p.product_id = b.id and p.id_dealer = '$dealer')
此查询使用LIMIT '1'
大约需要58秒,如果没有,我甚至不会得到回复。
删除and exists(select id from dealer_products p where p.product_id = b.id and p.id_dealer = '$dealer')
会使响应时间降至0.78秒,以返回相同的1个结果。
有没有办法改进这个查询,以便它不会花费这么荒谬的时间?
答案 0 :(得分:2)
exists(select id from dealer_products p where p.product_id = b.id and p.id_dealer = '$dealer')
而不是你可以使用
b.id in (select id from dealer_products p where p.product_id = b.id and p.id_dealer = '$dealer')
答案 1 :(得分:0)
亲爱的回答指出了我正确的方向。
仍然使用select([t]).where(getattr(t.c, col_name1) == "foo")
未返回正确的值。
要解决此问题,我已将其更改为b.id in (select id from dealer_products p where p.product_id = b.id and p.id_dealer = '$dealer')
。工作得很好,响应时间0.012秒。
答案 2 :(得分:0)
请使用JOIN ... ON
语法:
SELECT ...
FROM orders AS o
JOIN order_products AS op ON op.order_id = o.id
JOIN products AS p ON p.id = op.product_id
WHERE o.status = 2
AND o.seller_id = '...'
AND EXISTS(
SELECT * -- Note: no need for `id`
FROM dealer_products
WHERE product_id = p.id
AND id_dealer = '...'
)
所需索引:
orders: INDEX(status, seller_id, id) -- in either order
order_products: INDEX(order_id, product_id) -- "covering"
products: INDEX(id) -- but not if it is already PRIMARY KEY(id)
dealer_products: INDEX(id_dealer, product_id) -- note slight change in subquery
另外,请按照Many:Many mapping tables中的提示进行操作。