Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

query for single table with parent/child relations 1

Status
Not open for further replies.

gacaccia

Technical User
May 15, 2002
258
US
i have a single "tasks" table with a taskID primary key and a parentID field. the parentID field is an "informal" foreign key in that i've not establish a formal relation between the taskID field and the parentID field.

tasks
---------------
taskID
parentID
task
...


i need a query that will return all "parent" task records that only have one child record where the child record itself is not a parent of anything else.

i know how to make a query that will return all parent tasks with child tasks, but i'm not sure how to limit it to only parents tasks with one child task.

thanks for any help,

glenn
 

Code:
 select count(*) as counter, parentID
from myTable
group by parentID
having count(*) = 1) tmp )

this should help you limit to only one item. Dont have time to test, but then perform other part of your query

"I'm living so far beyond my income that we may almost be said to be living apart
 
thanks, that helped. my final query looks like...

Code:
select * from tasks as ct inner join tasks as pt on ct.parentID = pt.taskID 
where pt.taskID in (select parentID from tasks group by parentID having count(*) = 1)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top