views:

40

answers:

2

Background:


i have 2 tables:

Components: (id, name)

Dependencies: (id, hasaComponentId, isaComponentId)

in this case the hasaComponentId and isaComponentId are both foreign keys into the components table joined by components.id

Question


i have a set of Ids that the user selects. I want a sql query that will delete records from the dependencies tables where any of the ids in my list of ids is either in the hasaComponentId field or the isaComponentId field.

what is the best sql for this action?

+1  A: 
DELETE FROM Dependencies WHERE hasaComponentId In (YOUR OTHER QUERY);
DELETE FROM Dependencies WHERE isaComponentId  In (YOUR OTHER QUERY);

OR

DELETE FROM Dependencies WHERE hasaComponentId In (YOUR OTHER QUERY) OR 
                               isaComponentId  In (YOUR OTHER QUERY);
Adam Matan
I'd use EXISTs, but otherwise this would do it
gbn
what would be in (YOUR OTHER QUERY) . . i just have a list of ids coming from another source. i have updated the question to clarify that
ooo
If they came from another query, like (SELECT X FROM Y), put that query in braces.
Adam Matan
gotcha . . in this case its not from another query but out of curiosity, it would dynamically know that the result of the select query is a list of single fields ?
ooo
+1  A: 
DELETE Dependencies
FROM Dependencies d, Components c
WHERE
 (  
  (c.id=d.hasaComponentID and d.isaComponentID is null)
  OR
  (c.id=d.isaComponentID and d.hasaComponentID is null)
 )
     AND c.id IN (1,2,3,5)

Not tested, but looks right. Make sure you perform a SELECT first!

Wim Hollebrandse
i am getting an error here - syntax error near "d"
ooo
Not sure why you're getting that. Also - edited for null check.
Wim Hollebrandse