MySQL: limit results to items with at least one child item

Posted on 2011-05-04
Last Modified: 2012-06-21
With MySQL, I want to limit results to items with at least one child item.

My table has a column named `ParentID` and I only want results where at least one item uses the item returned as its `ParentID`

SELECT `Name`,`ID` FROM `File` WHERE `ClassName` = 'Folder' AND  (there is at least one `File` with the `ParentID` of this `ID`)

Open in new window

Question by:hankknight
    LVL 82

    Assisted Solution

    SELECT `Name`,`ID` FROM `File` WHERE `ClassName` = 'Folder' 
    AND  `File`.`ID` IN (SELECT `f2`.`ID` FROM `File` as `f2` WHERE `f2`.`ID`=`File`.`ID`)

    Open in new window

    LVL 15

    Accepted Solution

    SELECT `Name`,`ID` FROM `File` F1 WHERE `ClassName` = 'Folder' AND  exists (select 1 from `File` where `parentid` = F1.`ID` group by `parentid` having count(1) >=1)
    LVL 16

    Author Comment

    Thank you both.  hielo, I modified your code to make it work.  

    wpcortes, your code works as is.

    SELECT `Name`,`ID` FROM `File` WHERE `File`.`ClassName` = 'Folder' 
    AND `File`.`ID` IN (SELECT `f2`.`ParentID` FROM `File` as `f2` WHERE `f2`.`ParentID`=`File`.`ID`)

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    More Fun with XML and MySQL – Parsing Delimited String with a Single SQL Statement Are you ready for another of my SQL tidbits?  Hopefully so, as in this adventure, I will be covering a topic that comes up a lot which is parsing a comma (or other…
    As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now