Can a foreign key be created if both fields are no

2019-03-06 01:30发布

I have 2 database tables below I am thinking of creating:

Question Table:

QuestionId(PK)  QuestionNo  QuestionContent  SessionId (FK)
11              1           Question1        3    
12              2           Question2        3
13              3           Question3        3

Image_Question

ImageId (PK)  SessionId (Fk)  QuestionNo (FK)
1              3               1
2              3               2

Because of the way I set up an image upload, the user can upload images to a question before the question is submitted into db, so only way to determine which question an image belong to in my html was to use the QuestionNo in the html to know which question uploaded the image file as QuestionId is not entered until page is submitted.

My question is that is it possible to have 2 non unique fields as foreign keys?

Also if I just set SessionId as (FK) on its own and if QuestionNo allows (FK), that is set on its own thn prblem I have as that as there are multiple sessions with same QuestionNo, if I click on a QuestionNo above, it could displays rows for the same QuestionNo in all sessions that contain thatQuestionNo.

My other question will be how to combine SessionId and QuestionNo (FK) so that if I search under QuestionNo, it searches for that QuestionNo in the relevant SessionId? If I click on the SessionId then it displays details for that SessionId so that is ok.

标签: mysql sql mysqli
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-06 01:46

I find your question a little hard to understand, but from what I can gather you are using QuestionNo as a temporary token to link several http requests together (image uploads + question post).

I suggest something like:

SessionQuestionToken
{
  Token
  SessionId
}

Image
{
  ID
  QuestionId FK references Question(Id)
  ImageName
}

Question
{
  Id
  Content
}

TempImage
{
  Token FK references SessionQuestionToken(token)
  ImageName
}

And the logic like so:

  1. User requests question form. Server sets token and includes in response to user.
  2. User uploads picture including token. Image is stored in temporary table.
  3. Step 2 repeated n times.
  4. If user submits question with token value, an entry is placed in the questions table and an id is assigned. All images in the TempImage table that share the token get inserted to the image table with the now known QuestionId. The SessionQuestionToken entry is then deleted and cascade deletes the temp images in TempImage.
  5. Else user doesn't submit question then files are deleted and SessionQuestionToken entry deleted.

As for your question if foreign keys can still reference non unique columns, the answer is yes.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-06 01:55

You can reference multiple foreign keys in your table. Just make sure that your primary key is unique.

查看更多
登录 后发表回答