How to select parent row only if has at least one child?

Posted by Matt McCormick on Stack Overflow See other posts from Stack Overflow or by Matt McCormick
Published on 2010-04-03T16:15:51Z Indexed on 2010/04/03 16:23 UTC
Read the original article Hit count: 276

Filed under:
|
|
|
|

I have a simple one-to-many relationship. I would like to select rows from the parent only when they have at least one child. So, if there are no children, then the parent row is not returned in the result set.

Eg.

Parent:
+--+---------+
|id|   text  |
+--+---------+
| 1|  Blah   |
| 2|  Blah2  |
| 3|  Blah3  |
+--+---------+

Children
+--+------+-------+
|id|parent| other |
+--+------+-------+
| 1|   1  | blah  |
| 2|   1  | blah2 |
| 3|   2  | blah3 |
+--+------+-------+

I want the results to be:

+----+------+
|p.id|p.text|
+----+------+
|  1 | Blah |
|  2 | Blah2|
+----+------+

© Stack Overflow or respective owner

Related posts about sql

Related posts about mysql