2013-11-05 55 views
5

我想從多個具有多個外鍵的表中選擇sqlite中的結果,我試過JOIN,但它不能很好地工作;例如:如何從多個具有多個外鍵的表中選擇sqlite結果

STUDENT表:

CREATE TABLE STUDENT (
STUDENT_NAME TEXT  NOT NULL, 
STUDENT_NUMBER INTEGER PRIMARY KEY NOT NULL, 
STUDENT_ADDRESS TEXT  NOT NULL 
); 

EXAMS表:

CREATE TABLE EXAMS(
EXAM_CODE  INTEGER PRIMARY KEY NOT NULL, 
EXAM_SUBJECT TEXT  NOT NULL, 
EXAM_LOCATION TEXT  NOT NULL 
); 

和一個叫WROTE_EXAM讓學生是誰寫的具體考試信息表

CREATE TABLE WROTE_EXAM (
STUDENT_NUMBER INTEGER  NOT NULL, 
EXAM_CODE  INTEGER  NOT NULL, 
DATE   DATE  NOT NULL, 
FOREIGN KEY(STUDENT_NUMBER) REFERENCES STUDENT(STUDENT_NUMBER), 
FOREIGN KEY(EXAM_CODE) REFERENCES EXAMS(EXAM_CODE)); 

這是一個樣本數據i nserted到表:

STUDENT_NAME : John 
STUDENT_NUMBER: 123456789 
STUDENT_ADDRESS : 10th street 
EXAM_CODE: 123 
EXAM_SUBJECT: One Subject 
EXAM_LOCATION: Class 

現在,我想:
一)輸出學生姓名,考試代碼和學生的位置,誰寫的考試
B)輸出考試代碼,考試科目和考試地點爲學生與ID:123456789

感謝

+0

你嘗試過什麼JOIN? –

+0

@ muistooshort我做了'SELECT DISTINCT STUDENT_NAME,EXAM_CODE,STUDENT_LOCATION FROM WROTE_EXAM,STUDENT JOIN EXAMS,STUDENTS'不知道如何將3張桌子連接在一起並獲取此信息 –

回答

10

當聯接表,你幾乎總是要包括一個明確的連接條件。 SQLite的syntax diagrams可能會有所幫助:

Join Op Join Constraint

所以從您的評論的SQL應該看起來更像是這樣的:

select student.student_name, exams.exam_code, ... 
from student 
join wrote_exam using (student_number) 
join exams using (exam_code) 
where ... 

或者你可以使用JOIN ... ON:

select student.student_name, exams.exam_code, ... 
from student 
join wrote_exam on student.student_number = wrote_exam.student_number 
join exams on exams.exam_code = wrote_exam.exam_code 
where ... 

然後添加where條件以根據需要過濾結果。

請注意,我還添加了一些表預選賽列的SELECT子句中,那些需要唯一指定exam_code你有興趣,自一列需要合格的,我做了他們全部的一致性;在現實生活中,我會將它們全部加上前綴以使事情變得更加美好和明確

此外,我沒有在任何地方看到student_location,也許你的意思是student.student_addressexams.exam_location

+0

感謝您的幫助 –