sql (mysql) 优化查询或模式,避免全表扫描
我有一张包含数据的表。该表包含订单条目,每个订单都有一些类型(或状态,例如订购、...、抛光、包装、发货)。
现在,我想做这个查询。
select * from orders as o
where not exists
(SELECT * from orders as oo
where
o.order = oo.order and
oo.type="SHIPMENT")
类型和发货都有索引,但只有在进行全面扫描后才会使用。所以查询需要很长时间。我想直接展示数据。
I have one table with data. The table has entries for orders, each order has some types (or state e.g ordered, ..., polished, packed, shipped).
Now, I want to do this query.
select * from orders as o
where not exists
(SELECT * from orders as oo
where
o.order = oo.order and
oo.type="SHIPMENT")
type and shipment have a index, but it is only used after doing a full scan. So the query takes far to long. I want to present the data directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
orders.type
上有索引并不一定意味着将使用该索引。事实上,如果索引的选择性不够,就不会被使用。另外,如果您使用 NOT IN 或 LEFT JOIN/IS NULL 方法而不是 NOT EXISTS 方法,mysql 的工作速度会更快一些:Having an index on
orders.type
doesn't necessarily mean that this index will be used. In fact, the index is not used if it's not selective enough. Also, mysql works a little faster if you useNOT IN
orLEFT JOIN/IS NULL
approach instead ofNOT EXISTS
: