我的sql超时如果其中不包括主键组合的所有列?怎么了? [英] my sql timeouts if where doesnot include all columns of primary key combo? whats wrong?
问题描述
SHOW CREATE TABLE meter_data返回 -
CREATE TABLE`meter_data`(
`DeviceID` varchar(45) NOT NULL,
`MeterID` int(11)NOT NULL,
`TimeStamp` int(11)NOT NULL,
`W` float NOT NULL,
`F` float NOT NULL,
`PF1` float NOT NULL,
`V1` float NOT NULL,
`A1` float NOT NULL,
`PF2` float NOT NULL,
`A2` float NOT NULL,
`PF3` float NOT NULL,
`A3` float NOT NULL,
`FwdHr` float NOT NULL,
PRIMARY KEY `,`MeterID`,`TimeStamp`),
KEY`MeterID`(`MeterID`,`DeviceID`,`TimeStamp`)
)ENGINE = InnoDB DEFAULT CHARSET = utf8
有什么问题吗?
解决方案从 MySQL doc :MySQL如果列不是从索引的最左前缀开始,则不能使用索引执行查找。
问题不是不是全部复合键的部分包含在WHERE子句中,但是列不从最左侧的索引列开始。
如果你有索引(col1,col2,col3),在这种情况下最左边的索引列是col1,
然后
WHERE col1 = x AND col2 = y
和
WHERE col1 = x AND col2 = y AND col3 = z
将使用索引,但
WHERE col2 = x AND col3 = y
不会。
通过连接列值,如果col1 = x,col2 = y和col3 = z,则索引值将为 xyz
。在最后一个WHERE子句中,MySQL不能查看索引,因为索引的第一个(最左边的)部分没有使用。
在你的情况下,使用c $ c> MeterID
, DeviceID
)或( MeterID
,在WHERE子句中的DeviceID
, TimeStamp
)将导致索引搜索,但例如( DeviceID
, TimeStamp
)或( DeviceID
)或 TimeStamp
)将导致表扫描。
SHOW CREATE TABLE meter_data returns -
CREATE TABLE `meter_data` (
`DeviceID` varchar(45) NOT NULL,
`MeterID` int(11) NOT NULL,
`TimeStamp` int(11) NOT NULL,
`W` float NOT NULL,
`F` float NOT NULL,
`PF1` float NOT NULL,
`V1` float NOT NULL,
`A1` float NOT NULL,
`PF2` float NOT NULL,
`A2` float NOT NULL,
`PF3` float NOT NULL,
`A3` float NOT NULL,
`FwdHr` float NOT NULL,
PRIMARY KEY (`DeviceID`,`MeterID`,`TimeStamp`),
KEY `MeterID` (`MeterID`,`DeviceID`,`TimeStamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
whats wrong with it?
解决方案 From MySQL doc: "MySQL cannot use the index to perform lookups if the columns do not start form a leftmost prefix of the index."
The problem is not when not all parts of the composite key are included in the WHERE clause but when the columns don't start from the leftmost index column.
E.g. if you have index(col1, col2, col3) in which case the leftmost index column is col1,
then
WHERE col1 = x AND col2 = y
and
WHERE col1 = x AND col2 = y AND col3 = z
WILL use the index, but
WHERE col2 = x AND col3 = y
will NOT.
This is because the index is created by concatenating the column values so if col1=x, col2=y and col3=z then the index value will be x-y-z
. In the last WHERE clause MySQL cannot look at the indices because the first (leftmost) part of the index isn't used.
In your case, using either (MeterID
,DeviceID
) or (MeterID
,DeviceID
,TimeStamp
) in the WHERE clause will result in indexed search, but e.g. (DeviceID
,TimeStamp
) or (DeviceID
) or (TimeStamp
) will result in table scan.
这篇关于我的sql超时如果其中不包括主键组合的所有列?怎么了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!