Lets say I have a table named my_table with primary_key table_pk and with three nullible fields (foreign keys) named X_fk, Y_fk, and Z_fk respectively, and one other field called data. Tables X, Y, and Z all have a primary key field and a name field (e.g. {X_pk, X_name}, {Y_pk, Y_name}, {Z_pk, Z_name}).
I want a query that uniquely returns a row from my_table given the names in tables X, Y, and Z.
SELECT table_pk
FROM my_table
WHERE
X_fk = (SELECT X_pk FROM X WHERE X_name = ?)
AND
Y_fk = (SELECT Y_pk FROM Y WHERE Y_name = ?)
AND
Z_fk = (SELECT Z_pk FROM Z WHERE Z_name = ?)
This doesn’t work though when I want to find the row (X_Name, Y_Name, Z_Name) = (‘XXX’, ‘YYY’, NULL) because Z_fk = NULL can never result in TRUE. How can I modify the above query to pull out a unique entry from the table accounting for unique entries where some of the foreign keys are NULL?
Try this: