我有4個表,即:表的關係,我只能加入一個,如果其他表相關
tbl_users
tbl_college
tbl_courses
tbl_sections
tbl_users
包含當然,username
的,password
如果我想取所有關於某個用戶的信息,包括:
他/她是否屬於哪個學院(如工程學院或工商管理學院)
他/她正在上哪門課程(例如, 理學士土木工程,或者在營銷理學士)
什麼部分是他/她進入(例如CBC或資訊科技教育)
如果tbl_courses
是設置像這樣:
tbl_courses (id, course_name, college_id)
其中college_id
指tbl_college.id
和tbl_sections是設置這樣的:
tbl_sections(id, section_name, course_id)
其中course_id
指tbl_course.id
我應該怎麼做,選擇所有那些與用戶信息這這種情況是有username
,password
,college
,course
,section
我有想到的是,我可以即創建另一個表:tbl_user_section
,像這樣:
CREATE TABLE tbl_user_section (user_id INTEGER NOT NULL, section_id INTEGER NOT NULL,
FOREIGN KEY user_id REFERENCES users(id),
FOREIGN KEY section_id REFERENCES sections(id))
所以我可以有持有誰是哪個部門的表格。此外,通過把它在我看來,這樣我可以很容易地執行連接來獲取相關的信息:
SELECT tbl_users.username, tbl_sections.section_name FROM tbl_users
INNER JOIN tbl_user_section ON tbl_users.id = tbl_user_section.user_id
INNER JOIN tbl_sections ON tbl_sections.id = tbl_user_section.section_id
我有這種設置的最近遇到的問題是,如果用戶還沒有在節時,當我嘗試使用上面的代碼查詢所有用戶,該用戶不會被選中,否則不會顯示。
而且具有這種設置的我大概可以做到這一點
SELECT tbl_users.username, tbl_sections.section_name,
tbl_courses.course_name, tbl_colleges.college_name FROM tbl_users
INNER JOIN tbl_user_section ON tbl_users.id = tbl_user_section.user_id
INNER JOIN tbl_sections ON tbl_sections.id = tbl_user_section.section_id
INNER JOIN tbl_courses ON tbl_courses.id = tbl_sections.course_id
INNER JOIN tbl_colleges ON tbl_college.id = tbl_courses.college_id
要提取包含在查詢這些信息。
在您看來,您可以從我創建的設置中看到哪些其他問題?
在tbl_users中只有section_id
字段而不是像我一樣創建一個單獨的表是否更明智?
如果我有類型的用戶,我應該做同樣的(分開的用戶類型的表格),並有一個tbl_user_type
或只是讓他們在同一個表tbl_users
想這是個大工程,你會選擇什麼?
+1用於回答和消除我的困惑。等待更多答案 –