Jump to content

simplify a double query


LoOpy

Recommended Posts

Hi im not sure if this has been talked about because im not sure how to search for what im after. Im running MYSQL 4.1. Basicaly i have a single table with and id and parent_id to ref another row in the same table now at the moment in querying the table twice. So what im after is just 1 query to do the same job.

 

CREATE TABLE IF NOT EXISTS `database` (
  `id` tinyint(4) NOT NULL auto_increment,
  `parent_id` tinyint(4) NOT NULL,
  `name` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

 

query 1

SELECT id FROM database WHERE id = 'someid'

query2

SELECT id,name FROM database WHERE parent_id = 'query1_Id'

 

hope iv explained what im after.

Link to comment
Share on other sites

From what I can see you're looking for all the children of a particular parent.

Thus:

SELECT c.id
      ,c.name 
FROM `database` p
JOIN `database` c ON c.parent_id = p.id
WHERE p.id = 'someid'

 

p stands for parent

c stands for child

 

This is more commonly called a "self join".

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.