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

Posted on 2011-05-04
Medium Priority
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

hielo earned 800 total points
ID: 35694990
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 16

Accepted Solution

Walter Ritzel earned 1200 total points
ID: 35694993
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

ID: 35695019
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


Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
In this article, we’ll look at how to deploy ProxySQL.
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

850 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