【发布时间】:2013-06-25 14:35:25
【问题描述】:
我有以下数据库结构:
create table Accounting
(
Channel,
Account
)
create table ChannelMapper
(
AccountingChannel,
ShipmentsMarketPlace,
ShipmentsChannel
)
create table AccountMapper
(
AccountingAccount,
ShipmentsComponent
)
create table Shipments
(
MarketPlace,
Component,
ProductGroup,
ShipmentChannel,
Amount
)
我在这些表上运行以下查询,我正在尝试优化查询以尽可能快地运行:
select Accounting.Channel, Accounting.Account, Shipments.MarketPlace
from Accounting join ChannelMapper on Accounting.Channel = ChannelMapper.AccountingChannel
join AccountMapper on Accounting.Accounting = ChannelMapper.AccountingAccount
join Shipments on
(
ChannelMapper.ShipmentsMarketPlace = Shipments.MarketPlace
and ChannelMapper.AccountingChannel = Shipments.ShipmentChannel
and AccountMapper.ShipmentsComponent = Shipments.Component
)
join (select Component, sum(amount) from Shipment group by component) as Totals
on Shipment.Component = Totals.Component
如何让这个查询尽可能快地运行?我应该使用索引吗?如果是这样,我应该索引哪些表的哪些列?
这是我的查询计划的图片:
谢谢,
【问题讨论】:
-
索引是必不可少的。
WHERE子句中的任何内容都是索引的候选对象。您可以发布实际架构而不是您的抽象版本吗? -
数据建模至关重要。首先:将一些真实类型(可能是域)添加到您的列中。第二:PK/FK 约束是基本的。第三:(根据经验)如果表似乎有两个以上的候选键,它们是可疑的。您的 channelmapper 和 shipping 表可能存在这种现象(可能是 BCNF 或 4NF 违规),但您没有显示任何候选键,甚至语义也很模糊。
标签: mysql sql database optimization