SELECT Query where only one of three fields containing Foreign Keys is filled
题
As shown below the Table Recording
contains three foreign keys, only one of which will be filled for any one entry. My question is how can I format a select statement in Access that will only pull the names from the relevant table given the foreign key for that table?
I have tried using IIf, which works when checking which Foreign Key is Not Null after the SELECT:
SELECT Recording.[idRecording],
IIf(Recording.[Artist_idArtist] Is Not Null,
Artist.[artName] ,
IIf(Recording.[Band_idBand] is Not Null,
Band.[bName],
Composer.[cName]))
FROM ...
But putting any conditions after the FROM statement, to get the correct JOIN, results in an error:
FROM
IIf(Recording.[Artist_idArtist] Is Not Null,
Artist INNER JOIN Recording ON Recording.[Artist_idArtist] = Artist.[idArtist],
IIf(Recording.Band_idBand Is Not Null,
Band INNER JOIN Recording ON Recording.[Band_idBand] = Band.[idBand],
Composer INNER JOIN Recording ON Recording.[Composer_idComposer] = Composer.[idComposer]));
I'm new to this so I'm probably missing something obvious, or going about it the wrong way. I believe what I've ended up with here is an Exclusive Arc? I'm not sure if this is even a good design, I had thought of scrapping the Recording table and simply adding the foreign keys to Track.
For reference here is the Relationship Design:
解决方案
You can solve the problem with LEFT JOINs
SELECT
R.idRecording,
Nz(A.artName, Nz(B.bName, C.cName))
FROM
((Recording R
LEFT JOIN Artist A
ON R.Artist_idArtist = A.idArtist)
LEFT JOIN Band B
ON R.Band_idBand = B.idBand)
LEFT JOIN Composer C
ON R.Composer_idComposer = C.idComposer
They return all the records form the table on the left side and only the records from the table on the right side for which the join condition is met.
I also simplified the IIf
cascade with the Nz
function, which returns the second argument when the first one is null
.
I also use short aliases for table names, thus simplifying the query further.