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

tableの各列の値を取得できるように、school_dbtable で table を 3 回結合する必要があります。student_dbstudent_db

school_dbもう1つ、サーバーがどのテーブルと列が結合されているかを識別できるように、テーブルでエイリアスを一意に定義する必要があります。

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

あなたの間違いは、1つの学校のテーブルを持つテーブルの生徒と3回参加することですが、あなたの問題は、3つの学校を持つ1人の生徒についてです。

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 に答える
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 に答える