我想知道如何使用内部连接器以其他方式选择一列两次。我的数据库是sqlite,我使用的是PDO db驱动程序。
我的例子:
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
我还想得到编辑此记录的user_name
orders.edited_by = users.id
如何加入此选择?
答案 0 :(得分:9)
您需要使用表别名。
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
答案 1 :(得分:1)
在表名中使用aliases,这样就可以对同一个表使用多个引用。这也有助于使大型查询更易于阅读。
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
您可以根据需要使用同一桌子的任意数量的“实例”。