Join table on self

I am trying to select all rows in a table where the parent id is the passed value, but I also want to select all rows whose parent id equals the above selected rows ID

Example structure
tbl_categories_id    category_name    category_parent
1                                 cat1                                 1
2                                 cat2                                 1
3                                 cat3                                 1
4                                 cat4                                 2
5                                 cat5                                 2

So select all rows where the category_parent=1, but of those there is one (tbl_categories_id=2) which has 2 child rows (4 & 5)

How would I write the sql?

http://sqlfiddle.com/#!2/097e0/2
LVL 58
GaryAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SharathData EngineerCommented:
So if you pass category_parent as 1, you want all its children and their children in a recursive way?
GaryAuthor Commented:
Yep. So even though I am selecting where parent_id=1 my query should return

1                                 cat1                                 1
2                                 cat2                                 1
     4                                 cat4                                 2
     5                                 cat5                                 2
3                                 cat3                                 1
SharathData EngineerCommented:
check this.
    SET NAMES utf8;
    SET foreign_key_checks = 0;
    SET time_zone = '+01:00';
    SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
    
    DROP TABLE IF EXISTS `categories`;
    CREATE TABLE `categories` (
      `tbl_categories_id` int(11) NOT NULL AUTO_INCREMENT,
      `category_name` varchar(100) DEFAULT NULL,
      `category_parent` int(2) DEFAULT '0',
    
      UNIQUE KEY `tbl_categories_id` (`tbl_categories_id`)
    
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    
    -- 2013-10-17 22:40:09
    
    INSERT INTO `categories` (`tbl_categories_id`, `category_name`, `category_parent`) VALUES
    (1,	'cat1',	0),
    (2,	'cat2',	1),
    (3,	'cat3',	1),
    (4,	'cat4',	1),
    (5,	'cat5',	2),
    (6,	'cat6',	3)

**Query 1**:

    SELECT * 
      FROM categories 
     WHERE category_parent = 1 
        OR category_parent IN (SELECT tbl_categories_id 
                                 FROM (SELECT @r := (SELECT MIN(tbl_categories_id) 
                                                       FROM categories 
                                                      WHERE category_parent = @r) AS tbl_categories_id
                                         FROM (SELECT @r := 1) vars, 
                                              categories) t1) 

**[Results][2]**:
    
    | TBL_CATEGORIES_ID | CATEGORY_NAME | CATEGORY_PARENT |
    |-------------------|---------------|-----------------|
    |                 2 |          cat2 |               1 |
    |                 3 |          cat3 |               1 |
    |                 4 |          cat4 |               1 |
    |                 5 |          cat5 |               2 |

Open in new window

http://sqlfiddle.com/#!2/097e0/12

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

GaryAuthor Commented:
Will get back to this tomorrow, got into the middle of something else and don't want to get sidetracked.
SharathData EngineerCommented:
Thanks Paul for posting the sqlfiddle from my post. will post the solution going forward.
PortletPaulEE Topic AdvisorCommented:
:) no problem Sharath. Cheers, Paul.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.