1

Say I have two tables. new_dogs and name_color_pairs.

The records in name_color_pairs must be unique pairs.

new_dogs
---------
Name
Location Found
Color
Breed


name_color_pairs
---------
name
color

How can I select the name/color pairs from new_dogs that aren't currently in the name_color_pairs table so that they can be inserted?

1
  • 1
    You should write database, that you are using. Is it MySQL? Commented Oct 29, 2011 at 23:13

1 Answer 1

4
SELECT name, color FROM new_dogs
EXCEPT
SELECT name, color FROM name_color_pairs

or

SELECT name, color FROM new_dogs nd
WHERE NOT EXISTS (SELECT name, color FROM name_color_pairs ncp WHERE (ncp.name = nd.name) AND (ncp.color = nd.color))

or finally (should be working everywhere):

SELECT name, color FROM new_dogs nd
LEFT JOIN name_color_pairs ncp
ON (ncp.color = nd.color) AND (ncp.name = nd.name)
WHERE ncp.name IS NULL
Sign up to request clarification or add additional context in comments.

1 Comment

any chance you know how to solve this related question? stackoverflow.com/questions/7942650/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.