如何从多个表中选择数据?
我有 4 个表,我对选择数据感到非常困惑。
的 4 个表中有此字段
t1 -> student_id
given_name
user_name
t2 -> school_year
sem
class
student_id
main_id
t3 -> subject_id
main_id
t4 -> subject_id
subject_name
我需要选择 (given_name、subject_name、class 和 main_id)。如何?
我尝试这样
SELECT t2.school_year, t2.rp_main_sem, t2.rp_main_class, t4.name, t4.subject_id, t1.given_name, t1.user_name FROM t1, t2, t3, t4 WHERE t2.school_year = 2011 AND t2.sem = 1 AND t2.class = 'ES3A' AND t3.subject_id = t4.subject_id AND t1.student_id = t2.rp_main_student_id
I have 4 tables, i am very confused to select the data.
I have this fields in my 4 tables
t1 -> student_id
given_name
user_name
t2 -> school_year
sem
class
student_id
main_id
t3 -> subject_id
main_id
t4 -> subject_id
subject_name
I need to select (given_name, subject_name, class & main_id). How?
I try like this
SELECT t2.school_year, t2.rp_main_sem, t2.rp_main_class, t4.name, t4.subject_id, t1.given_name, t1.user_name FROM t1, t2, t3, t4 WHERE t2.school_year = 2011 AND t2.sem = 1 AND t2.class = 'ES3A' AND t3.subject_id = t4.subject_id AND t1.student_id = t2.rp_main_student_id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这应该可以做到,但请告诉我们您需要什么形式的数据。您想获取每个学生的课程吗?或每个班级的学生人数?
this should do it but please tell us in what form you need the data. do you want to get the classes per student? or students per class?
您将需要加入表格。每个表都应该有一个主键(或唯一键)以及对其他表的引用(所谓的外键)。
因此,我们假设
t1
具有 PKstudent_id
t4
具有 PKsubject_id
t2
是一个关联表,用于链接学生(使用他们的student_id
)到具有main_id
的类。t3
是一个将主题链接到类的关联表。You will need to JOIN the tables. Each table should have a PRIMARY (or UNIQUE) key, and references (so called FOREIGN KEYs) to the other tables.
So we assume that
t1
has PKstudent_id
t4
has PKsubject_id
t2
is a associative table that links students (using theirstudent_id
) to classes, which have amain_id
.t3
is an associative table that links subjects to classes.尝试:
Try:
我想你需要这样的查询:
I guess you need a query like this: