2

I'm trying to design a database that contains, among others, entities "Photo", "Venues" and "Products". Given both Venues and Products could contain a collection of photos... how could I tell whether the photo is from a Venue or a product?

Photos
    Id PK
    Venue_Id FK
    Product_Id FK

Venues
    ID PK
    Photos_Id FK

Products
    ID PK
    Photos_Id Fk
2
  • Wait, in the table Venues and Products there is 1 FK Photos_Id, Does it come from Photos table? You want to know if photo if from a Venue or a Product? Can you alter those tables? Maybe if you provide us more information we can build you a better design.
    – oNare
    Commented Jul 12, 2015 at 3:40
  • Is there a name for some superclass that includes both venues and products as subclasses? There is a tag called subtypes that group together questions of that ilk. Commented Jul 12, 2015 at 8:39

1 Answer 1

2

There is likely something wrong with your model. Mutual dependencies are very rare in relational database designs. This is what I assume you want to do:

create table photos
( photo_id ... not null primary key
, <additional attributes> );

create table venues
( venue_id ... not null primary key
, photo_id ... not null
      references photos (photo_id) 
, <additional attributes> );

create table products
( product_id ... not null primary key
, photo_id ... not null
      references photos (photo_id) 
, <additional attributes> );

To determine whether a photo belongs to a venue, product or both you could do something like:

select x.photo_id
     , case when y.photo_id is not null then 'Venue' end
     , case when z.photo_id is not null then 'Product' end
from photos x
left join venues y
    on x.photo_id = y.photo_id
left join products z
    on x.photo_id = z.photo_id

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.