1

我想显示学生毕业的学校。我有一张学校名称表和一张学生资料表。这是我的代码:

school_db

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

学生数据库

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

问候,

4

3 回答 3

3

您应该在 tableschool_db上三次加入 table,student_db以便您可以获得 table 上每一列的值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'

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-02-19T15:37:42.643 回答
2

每个重新加入都必须有一个唯一的别名:

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

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

于 2013-02-19T15:35:56.370 回答
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'
于 2013-02-19T15:38:31.787 回答