如何从多个表中选择数据?

时间:2011-09-15 08:13:56

标签: mysql select multiple-tables

我有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

6 个答案:

答案 0 :(得分:0)

我想你需要这样的查询:

SELECT t1.given_name, t4.subject_name, t2.main_id
FROM t1
LEFT JOIN t2 ON t1.student_id = t2.student_id
LEFT JOIN t3 ON t2.main_id = t3.main_id
LEFT JOIN t4 ON t3.subject_id = t4.subject_id

答案 1 :(得分:0)

您需要加入表格。每个表都应该有一个PRIMARY(或UNIQUE)键,并引用(所谓的FOREIGN KEY)到其他表。

SELECT given_name , t4.subject_name, t2.class, t3.main_id
FROM t1 
JOIN t2 
ON t1.student_id = t2.student_id
JOIN t3
ON t2.main_id = t3.main_id
JOIN t4
ON t2.subject_id = t3.subject_id
WHERE t2.school_year = "2011""  and t2.sem = 1 --added where because of your comment

所以我们假设

  • 学生表t1有PK student_id
  • 主题表t4有PK subject_id
  • t2是一个关联表,用于链接学生(使用他们的 student_id}到具有main_id
  • 的班级
  • t3是一个将主题链接到类的关联表。

答案 2 :(得分:0)

   SELECT
      t1.given_name,
      t3.subject_name,
      t2.class,
      t2.main_id 
   FROM
      t1 
   JOIN
      t2 
         ON t1.student_id = t2.student_id 
   JOIN
      t3 
         ON t2.main_id = t3.main_id 
   JOIN
      t4 
         ON t3.subject_id = t4.subject_ID

这应该这样做,但请告诉我们您需要数据的形式。你想为每个学生上课吗?或每班学生?

答案 3 :(得分:0)

select t1.given_name, t4.subject_name, t2.class, t2.main_id
  from t1 
  join t2 on t1.student_id = t2.student_id
  join t2.main_id = t3.main_id
  join t3.subject_id = t4.subject_id

答案 4 :(得分:0)

尝试:

   SELECT t1.given_name, t4.subject_name, t2.class, t2.main_id
     FROM t1
LEFT JOIN t2
       ON t1.student_id = t2.student_id
LEFT JOIN t3
       ON t2.main_id = t3.main_id
LEFT JOIN t4
       ON t3.subject_id = t4.subject_id
    WHERE t2.school_year = 2011 
      AND t2.sem = 1

答案 5 :(得分:0)

SELECT table_name1.given_name,table_name4.subject_name,
table_name2.class,table_name2.main_id
FROM table_name1
INNER JOIN table_name2
ON table_name1.studen_id=table_name2.studen_id
INNER JOIN table_name3
ON table_name2.main_id=table_name3.main_id
INNER JOIN table_name4
ON table_name3.subject_id=table_name4.subject_id