Jump to content

[SOLVED] Optimising query with subqueries


tidalik

Recommended Posts

I have a query that works, but desperately needs to be optimised.

 

MySQL Ver: 5.0.45

The statement finds the number offspring of a nominated Sire or Dam who themselves have offspring.  In this case the nominated Sire or Dam is 1093.

The table index is PedigreeId, SireId/DamId are the PedigreeId of the Sire/Dam.

Table has at present 13 000 entries.

 

The query:

select count(PedigreeId) from peds where (SireId = 1093 OR DamId = 1093) 
AND (PedigreeId IN (select SireId from peds) OR PedigreeId IN (Select DamId from peds))

As you can see, selecting all the SireId and DamId in the entire db is overkill - but I don't know how best to select the PedigreeId who are either sires or dams.  The query works, it is just very slow.

 

Table structure:

CREATE TABLE `peds` (
  `PedigreeId` int(11) NOT NULL auto_increment,
  `Name` varchar(64) default NULL,
  `SireId` int(11) default NULL,
  `DamId` int(11) default NULL,
  `Sex` varchar(10) default NULL,
  `DOB` date default NULL,
  `PreTitle` varchar(32) default NULL,
  `PostTitle` varchar(32) default NULL,
  `RegNo` varchar(64) default NULL,
  `Color` varchar(64) default NULL,
  `Photo` varchar(200) default NULL,
  `COI` varchar(64) default NULL,
  `COO` varchar(64) default NULL,
  PRIMARY KEY  (`PedigreeId`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

 

Edited to stop query scrolling

Link to comment
Share on other sites

Found the answer myself.

 

The only way was to rewrite it as a join, went from running at 1.88 secs down to 0.31 secs

 

select count(DISTINCT p1.PedigreeId) from peds p1, peds p2 where (p1.SireId = 3023 OR p1.DamId = 3023) AND (p1.PedigreeId = p2.SireId OR p1.PedigreeId = p2.DamId)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.