Question

I am still working on a photo storage app (designing the database for the data for the photos stored), using MySQL, and have been told that a photo may have one or more people in it, and a person may be in many photographs, which makes sense.

My issue is in understanding the properties of the linking table between the photo and person tables. I have set up a linking table with the PK of both tables (Photo and Person) as the composite PK for the linking table. Both sets of PK in this table are set to Not Null (by me) but the project then stipulates that people can be in the database even if they aren't in a photo, and I was wondering how this tallies with the NN setting of the composite PK. Surely if it has to be NN, this means it can't allow for there to be any entries where I just have the PK of the photo and none for the person part of the linking table? Or am I totally misunderstanding how these relationships work? As mentioned previously, I am in the early stages of learning about databases.

Était-ce utile?

La solution

Actually you don't need a special value for people that aren't there

When you select a photo andand you don't know if there aren't any people in it, you make

SELECT p.*,pe.*
FROM Photo p 
   LEFT JOIN reftable r ON p.id = r.p_id 
   LEFT JOIN peope pe ON  r.pe_id = pe.id 
WHERE p.id = 123

So even when there is no entry in the Relationship table, you get an photo.

If you have one person and want to find all photos that they are in

SELECT pe.*,p.*
FROM peope pe  
   INNER JOIN reftable r ON r.pe_id = pe.id
   INNER JOIN Photo p  ON p.id = r.p_id  
WHERE pe.id = 123

You need here a relationship table, because many persons could be on a photo or one person can be in many photos

Licencié sous: CC-BY-SA avec attribution
Non affilié à dba.stackexchange
scroll top