简体   繁体   English

Mysql Join查询优化

[英]Mysql Join Query optimization

I have two tables in mysql: 我在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. 现在,如果我只想排前5行,大约需要5-6分钟。 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
SELECT  res.TIndex ,
        res.PNumber ,
        res.Sender ,
        res.Receiver ,
        sta.Nickname ,
        rta.Nickname
FROM    Results AS res
        INNER JOIN Nodes AS sta ON res.sender_h = sta.name
        INNER JOIN Nodes AS rta ON res.receiver_h = rta.NAME
  1. Create an index on Results (sender_h) 在结果上创建索引(sender_h)
  2. Create an index on Results (receiver_h) 在结果上创建索引(receiver_h)
  3. Create an index on Nodes (name) 在节点(名称)上创建索引

Joining on the node's name rather than NodeId (the primary key) doesn't look good at all. 联接节点name而不是NodeId (主键)看起来一点也不好。

Perhaps you should be storing NodeId for foreign key sender and receiver in the Results table instead of name Adding foreign key constraints is a good idea too. 也许您应该在Results表中存储外键senderreceiver NodeId而不是name添加外键约束也是一个好主意。 Among other things, this might cause indexing automatically depending on your configuration 除其他外,这可能会导致自动索引,具体取决于您的配置

If this change is difficult, at the very least you should enforce uniqueness on node 's name field 如果此更改很困难,则至少应在nodename字段上实施唯一性

If 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. 如果您以这种方式更改表定义,则将查询更改为John的建议,并添加索引,它应能更好地运行并且更具可读性/更好的形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM