Mysql Join 查询优化
我在 mysql 中有两个表:
Results Table : 1046928 rows.
Nodes Table : 50 rows.
我使用以下查询连接这两个表,并且查询的执行非常慢。
select res.TIndex, res.PNumber, res.Sender, res.Receiver,
sta.Nickname, rta.Nickname from ((Results res join
Nodes sta) join Nodes rta) where ((res.sender_h=sta.name) and
(res.receiver_h=rta.name));
请帮我优化这个查询。现在,如果我只想提取前 5 行,大约需要 5-6 分钟。谢谢。
CREATE TABLE `nodes1` (
`NodeID` int(11) NOT NULL,
`Name` varchar(254) NOT NULL,
`Nickname` varchar(254) NOT NULL,
PRIMARY KEY (`NodeID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `Results1` (
`TIndex` int(11) NOT NULL,
`PNumber` int(11) NOT NULL,
`Sender` varchar(254) NOT NULL,
`Receiver` varchar(254) NOT NULL,
`PTime` datetime NOT NULL,
PRIMARY KEY (`TIndex`,`PNumber`),
KEY `PERIOD_TIME_IDX` (`PTime`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I have two tables in mysql:
Results Table : 1046928 rows.
Nodes Table : 50 rows.
I am joining these two tables with the following query and the execution of the query is very very slow.
select res.TIndex, res.PNumber, res.Sender, res.Receiver,
sta.Nickname, rta.Nickname from ((Results res join
Nodes sta) join Nodes rta) where ((res.sender_h=sta.name) and
(res.receiver_h=rta.name));
Please help me optimize this query. Right now if I want to pull just top 5 rows, It takes about 5-6 MINUTES. Thank you.
CREATE TABLE `nodes1` (
`NodeID` int(11) NOT NULL,
`Name` varchar(254) NOT NULL,
`Nickname` varchar(254) NOT NULL,
PRIMARY KEY (`NodeID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `Results1` (
`TIndex` int(11) NOT NULL,
`PNumber` int(11) NOT NULL,
`Sender` varchar(254) NOT NULL,
`Receiver` varchar(254) NOT NULL,
`PTime` datetime NOT NULL,
PRIMARY KEY (`TIndex`,`PNumber`),
KEY `PERIOD_TIME_IDX` (`PTime`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(sender_h)
在节点(名称)上
(sender_h)
on Nodes (name)
连接节点的
name
而不是NodeId
(主键)看起来一点都不好。也许您应该在
Results
表中存储外键sender
和receiver
的NodeId
而不是name
添加外键约束也是一个好主意。除此之外,这可能会导致根据您的配置自动建立索引如果此更改很困难,那么至少您应该在
node
的name
字段上强制执行唯一性如果您更改以这种方式定义表,将查询更改为约翰的建议,并添加索引,它应该运行得更好,并且更具可读性/更好的形式。
Joining on the node's
name
rather thanNodeId
(the primary key) doesn't look good at all.Perhaps you should be storing
NodeId
for foreign keysender
andreceiver
in theResults
table instead ofname
Adding foreign key constraints is a good idea too. Among other things, this might cause indexing automatically depending on your configurationIf this change is difficult, at the very least you should enforce uniqueness on
node
'sname
fieldIf you change the tables definition in this manner, change your query to John's recommendation, and add indexes it should run a lot better and be a lot more readable/better form.