primary key and foreign key

2019-03-02 05:31发布

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

4条回答
ゆ 、 Hurt°
2楼-- · 2019-03-02 05:39

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.

查看更多
Bombasti
3楼-- · 2019-03-02 05:44

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

查看更多
\"骚年 ilove
4楼-- · 2019-03-02 05:45
Student
--------      
Studentid -PK

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


Book
-------
Bookid  -PK
Loanid   -FK
查看更多
姐就是有狂的资本
5楼-- · 2019-03-02 06:02

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)
);
查看更多
登录 后发表回答