sql, sqlite SELECT with inner join

2019-01-28 07:17发布

I'm wondering how to select one column twice using an inner joinor some other way. my database is sqlite and i use PDO db driver.

My Example:

    SELECT
            orders.id,
            orders.order_number,
            clients.first_name,
            clients.last_name,
            users.name AS user_name
    FROM orders

    INNER JOIN clients ON
            orders.client_id = clients.id

    INNER JOIN users ON
            orders.created_by = users.id

I want to get also, the user_name who edited this record

            orders.edited_by = users.id

How to join this selection?

标签: sql sqlite3 pdo
2条回答
做自己的国王
2楼-- · 2019-01-28 07:44

Use aliases in your table names, so you can use multiple references to the same table. This also can help make large queries easier to read.

SELECT
        orders.id,
        orders.order_number,
        clients.first_name,
        clients.last_name,
        createUsers.name AS creator_name,
        editUsers.name AS editor_name
FROM orders

INNER JOIN clients ON
        orders.client_id = clients.id

INNER JOIN users As createUsers ON
        orders.created_by = users.id

INNER JOIN users As editUsers ON
        orders.edited_by = users.id

You can use as many "instances" of the same table as you wish.

查看更多
Luminary・发光体
3楼-- · 2019-01-28 07:49

You'll need to use table aliases.

SELECT
        orders.id,
        orders.order_number,
        clients.first_name,
        clients.last_name,
        creator.name AS creator_user_name
        editor.name AS editor_user_name
FROM orders

INNER JOIN clients ON
        orders.client_id = clients.id

INNER JOIN users creator ON
        orders.created_by = creator.id

INNER JOIN users editor ON
        orders.edited_by = editor.id
查看更多
登录 后发表回答