内部连接从第一个表到第二个表的单个列的多个列

时间:2018-03-25 17:02:03

标签: mysql

我想在mysql的两个表中使用多个内连接,

table1有列"主题,考试时间,讲师,监护人,房间"

在我的table2中有列' subject1' ' subject2' ' subject3'

我想根据subject1,subject2,subject3在我的表2中显示我的table1中的主题,考试时间,教师等

到目前为止,我的代码是

select subject,examinationtime,instructor,proctor,room
                    from table1
                   inner join table2 on table1.subject=table2.subject1

到目前为止它适用于subject1但是如果我尝试添加subject2,则datagrid视图变为空白

这是我尝试的代码

select subject,examinationtime,instructor,proctor,room
                        from table1
                       inner join table2 on table1.subject=table2.subject1
                        and table1.subject=table2.subject2

我尝试使用'和'但datagrid视图变为空白。我想我需要使用别名,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

我的猜测是,您只需在查询中从and切换到or

select subject,examinationtime,instructor,proctor,room
from table1
inner join table2 on table1.subject=table2.subject1
or table1.subject=table2.subject2

答案 1 :(得分:0)

以下是您的查询,重写了如何使用表别名':

SELECT 
    a.subject,
    a.examinationtime,
    a.instructor,
    a.proctor,
    a.room
FROM table1 a
LEFT JOIN table2 b
    ON a.subject = b.subject1
LEFT JOIN table2 c
    ON a.subject = c.subject2
LEFT JOIN table2 d
    ON a.subject = d.subject3

这里的答案是一个应该产生你描述的结果的查询:

SELECT 
    b.subject,
    b.examinationtime,
    b.instructor,
    b.proctor,
    b.room
FROM table2 a
INNER JOIN table1 b
    ON a.subject1 = b.subject
        OR a.subject2 = b.subject
        OR a.subject3 = b.subject
相关问题