2014-09-05 88 views
0

我使用mySQL,我試圖找到一個表或另一個表中的行。 下面是表及其字段:從這兩個表中選擇值

user: id(PK), email, password, is_teacher 

teacher: id, no_teacher(PK), name, id_group, no_class 
teacher_information:no_teacher, cell_phone, SSN, email 

student: id, no_student(PK), name, id_group, no_class 
student_information:cell_phone, email, grade, no_student 

user_role: id, id_role(PK) 

group_leader: id_group, id_role 
group_member: id_group, id_role 

group: id_group(PK), name 

每個用戶(教師或學生)可以在一組組長或成員(不是兩個),並且任何用戶都可以在不同的組。 我想要列出與他的姓名和電子郵件有關的特定組中的每個人。 任何人都可以幫助我得到這個場景的sql查詢嗎?

+0

你的意思是你想擁有的組表中的記錄任何組的每個成員或者是你想過濾一個特定的組? – thaspius 2014-09-05 15:50:39

+0

儘量避免使用保留字作爲表格/列標識符 – Strawberry 2014-09-05 15:51:14

+0

我無法弄清楚你想要什麼。請添加示例數據和所需輸出。 – 2014-09-05 15:51:40

回答

0

如果你到teacher_information表和student_id添加一個字段teacher_id到student_information場

SELECT 
    * 
FROM  
    (SELECT 
     t.name as `name`, 
     ti.email as `email`, 
     g.name as `group_name`, 
     g.id_group as `id_group` 
    FROM 
     teacher t, 
     teacher_information ti, 
     group g 
    WHERE 
     t.id = ti.teacher_id and 
     g.id_group = t.id_group 
    UNION 
    SELECT 
     s.name as `name`, 
     si.email as `email`, 
     g.name as `group_name`, 
     g.id_group as `id_group` 
    FROM 
     student s, 
     student_information si, 
     group g 
    WHERE 
     s.id = si.student_id and 
     g.id_group = s.id_group 
    ) as a 
where 
    a.id_group = ? 
;