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?
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
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.