primary key and foreign key

丶灬走出姿态 提交于 2019-12-02 07:56:09

问题


I have 3 tables

   Student    Loan    Book
 - StudentID  LoanID  BookID

which foreign keys do i need to set so when given the student name, search all loan from that student and display the book detail


回答1:


Here's a start with such vague requirements:

CREATE TABLE dbo.Students
(
  StudentID INT PRIMARY KEY
  -- , other columns about students
);

CREATE TABLE dbo.Loans
(
  LoanID    INT PRIMARY KEY,
  StudentID INT NOT NULL FOREIGN KEY REFERENCES dbo.Students(StudentID)
  -- , other columns about loans
);

CREATE TABLE dbo.Books
(
  BookID INT PRIMARY KEY,
  -- , other columns about books
);

CREATE TABLE dbo.StudentBooks
(
  StudentID INT NOT NULL FOREIGN KEY REFERENCES dbo.Students(StudentID),
  BookID    INT NOT NULL FOREIGN KEY REFERENCES dbo.Books(BookID)
);



回答2:


Student
--------      
Studentid -PK

Loan
---------
Loanid  - PK
Studentid -FK


Book
-------
Bookid  -PK
Loanid   -FK



回答3:


Not sure what columns you have, assuming you have studentId in student table, it would be best candidate for primary in Student and foriegn in other two tables.




回答4:


you have to use studentid as foreign key in both the other tables...because you want to search on the basis of student. so this key should go in the remaining tables



来源:https://stackoverflow.com/questions/9237833/primary-key-and-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!