ホーム -> 7章 応用操作
prev 初心者向けSQL解説サイト 前へ 初心者向けSQL解説サイト トップへ 初心者向けSQL解説サイト 次へ next

7-1-3.外部結合

  • 左外部結合

    生徒名簿に載っている生徒の試験結果のデータを取得します。

    
    SELECT
     tbl_std.id,
     tbl_exam.eng,
     tbl_exam.math
    FROM
     tbl_std
    LEFT JOIN
     tbl_exam 
    ON
     tbl_std.id=tbl_exam.id;
    
    

    
    +-------+------+------+
    | id    | eng  | math |
    +-------+------+------+
    | 00001 |   85 |   85 |
    | 00002 |    0 |   95 |
    | 00005 | NULL | NULL |
    +-------+------+------+
    
    

  • 右外部結合

    生徒名簿に載ってない生徒を含めた試験結果のデータを取得します。

    
    SELECT
     tbl_std.id,
     tbl_exam.eng,
     tbl_exam.math
    FROM
     tbl_std
    RIGHT JOIN
     tbl_exam 
    ON
     tbl_std.id=tbl_exam.id;
    
    

    
    +-------+------+------+
    | id    | eng  | math |
    +-------+------+------+
    | 00001 |   85 |   85 |
    | 00002 |    0 |   95 |
    | NULL  |   90 |   55 |
    | NULL  |   55 | NULL |
    | NULL  | NULL |   55 |
    +-------+------+------+
    
    

  • 全外部結合

    FULL JOINはMySQLでは現在(ver5.1.33)の時点では、未サポートらしです。
    代替案としては下記に示すUNIONを使用するやり方があります。           

    
    SELECT
     tbl_std.id,
     tbl_exam.eng,
     tbl_exam.math
    FROM
     tbl_std
    LEFT JOIN
     tbl_exam 
    ON
     tbl_std.id=tbl_exam.id
    UNION
    SELECT
     tbl_std.id,
     tbl_exam.eng,
     tbl_exam.math
    FROM
     tbl_std
    RIGHT JOIN
     tbl_exam 
    ON
     tbl_std.id=tbl_exam.id;
    
    

    
    +-------+------+------+
    | id    | eng  | math |
    +-------+------+------+
    | 00001 |   85 |   85 |
    | 00002 |    0 |   95 |
    | 00005 | NULL | NULL |
    | NULL  |   90 |   55 |
    | NULL  |   55 | NULL |
    | NULL  | NULL |   55 |
    +-------+------+------+
    
    

prev 初心者向けSQL解説サイト 前へ 初心者向けSQL解説サイト トップへ 初心者向けSQL解説サイト 次へ next
inserted by FC2 system