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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Child/Parent table - "family" view 1

Status
Not open for further replies.

pwills

Technical User
Sep 14, 2002
54
GB
[NB. This is a derivative of a question posed on MS Sql Svr forum.]

I have a classic self-referring table
USER(USER_ID,PARENT)

I want to list all users in Bob's "family" i.e. Bob, children, parent, siblings.

Is the following query OK? Is it possible to avoid repeating the sub-select?

SELECT USER_ID FROM USER
WHERE
USER_ID = 'Bob' OR
PARENT = 'Bob' OR
USER_ID = (SELECT PARENT FROM USER WHERE USER_ID = 'Bob') OR
PARENT = (SELECT PARENT FROM USER WHERE USER_ID = 'Bob')
 
query looks okay at first glance (it gets bob's family okay, as far as i can tell)

any database worth its salt will see that the two subqueries are the same and not run it twice

you could try collapsing them like this

OR (SELECT PARENT FROM USER WHERE USER_ID = 'Bob')
IN ( USER_ID, PARENT )

rudy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top