mysql连接2个表,2列

时间:2012-12-09 14:53:59

标签: mysql sql

让我说我有

表格student_data和字段


╔════╦════════════╦════════════╗
║ ID ║ CREATED_BY ║ UPDATED_BY ║
╠════╬════════════╬════════════╣
║  1 ║          1 ║          2 ║
╚════╩════════════╩════════════╝

表格creator_updater和字段


╔════╦════════════════╗
║ ID ║      NAME      ║
╠════╬════════════════╣
║  1 ║ The Creator    ║
║  2 ║ Second Creator ║
╚════╩════════════════╝

所以我想知道确切的代码是什么,所以它会显示

student_data

╔════╦═══════════════╦══════════════════════╗
║ ID ║ CREATED_BY_ID ║ LATEST_UPDATED_BY_ID ║
╠════╬═══════════════╬══════════════════════╣
║  1 ║ The Creator   ║ Second Creator       ║
╚════╩═══════════════╩══════════════════════╝

我试过加入语法,但看起来不一样

1 个答案:

答案 0 :(得分:4)

您需要加入creator_updater表两次,以便获取两列的名称。

SELECT  a.id,
        b.name created_by_id,
        c.name latest_updated_by_id
FROM    student_data a
        INNER JOIN creator_updater b
            ON a.created_by = b.id
        INNER JOIN creator_updater c
            ON a.updated_by = c.id

但如果其中一列可以为空,则上述代码无效,如果是这种情况,请使用LEFT JOIN代替INNER JOIN

SELECT  a.id,
        b.name created_by_id,
        c.name latest_updated_by_id
FROM    student_data a
        LEFT JOIN creator_updater b
            ON a.created_by = b.id
        LEFT JOIN creator_updater c
            ON a.updated_by = c.id

有关联接的更多信息