如何使用相同的表但不同的条件连接另一个表

时间:2013-02-19 15:33:14

标签: mysql sql inner-join

我想展示一个学生毕业的学校。我有一张学校名称表和一份学生档案表。这是我的代码:

school_db

shc_id       shc_title
1            School A
2            School B
3            School C
4            School D
5            School E

student_db

stu_id       stu_school1         stu_school2           stu_school3
1                 1                   2                     2
2                 1                   2                     4
3                 2                   2                     4

所以我写道:

select school_db.sch_title as school from school_db
inner join student_db on student_db.stu_school1=school_db.shc_id
inner join student_db on student_db.stu_school2=school_db.shc_id
inner join student_db on student_db.stu_school3=school_db.shc_id
where student_db.stu_id='1'

但我未能得到正确的结果。那么请你在这种情况下建议如何使用正确的连接。

我希望结果如下:

stu_id        stu_school1         stu_school2           stu_school3
1             School A            School B              School B
2             School A            School B              School D
3             School B            School B              School D

此致

3 个答案:

答案 0 :(得分:3)

您应该在表school_db上加入表student_db三次,以便您可以获取表student_db上每列的值。

还有一件事,你应该在表school_db上唯一定义别名,这样服务器就可以识别表和列的连接。

SELECT  a.stu_id,
        b.shc_title sc1,
        c.shc_title sc2,
        d.shc_title sc3
FROM    student_db a
        INNER JOIN school_db b
            ON a.stu_school1 = b.shc_id
        INNER JOIN school_db c
            ON a.stu_school2 = c.shc_id
        INNER JOIN school_db d
            ON a.stu_school3 = d.shc_id
WHERE   a.stu_id = '1'

要进一步了解联接,请访问以下链接:

答案 1 :(得分:2)

每个重新连接必须具有唯一的别名:

INNER JOIN student_db AS db1 ON school_db.shc_id = db1.stu_school1
                      ^^^^^^                       ^^^
INNER JOIN student_db AS db2 etc...

至于你的结果,你想要的是一个数据透视查询,MySQL不直接支持。有解决方法,但它们非常丑陋且难以维护。您最好执行常规查询,然后在客户端中执行表格格式化。

答案 2 :(得分:2)

你的错误是与桌面学生一起参加3次学校课程,而你的问题是一个学生有3所学校:

SELECT 
    student_db.stu_id, 
    s1.sch_title as school1, 
    s2.sch_title as school2, 
    s3.sch_title as school3
FROM 
    student_db
        INNER JOIN school_db s1 ON student_db.stu_school1=s1.shc_id
        INNER JOIN school_db s2 ON student_db.stu_school2=s2.shc_id
        INNER JOIN school_db s3 ON student_db.stu_school3=s3.shc_id
WHERE student_db.stu_id='1'

但是,如果不是总有3所学校,你应该表明:

SELECT 
    student_db.stu_id, 
    s1.sch_title as school1, 
    IFNULL(s2.sch_title, 'No school selected') as school2, 
    IFNULL(s3.sch_title, 'No school selected') as school3
FROM 
    student_db
        INNER JOIN school_db s1 ON student_db.stu_school1=s1.shc_id
        LEFT JOIN school_db s2 ON student_db.stu_school2=s2.shc_id
        LEFT JOIN school_db s3 ON student_db.stu_school3=s3.shc_id
WHERE student_db.stu_id='1'