开发者

Mysql Join Query optimization

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, 开发者_如何学Gores.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


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)
  2. Create an index on Results (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.

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. 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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜