简体   繁体   中英

How can I write this SQL SELECT query?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM