[英]How to run two LEFT joins from the same two tables, but to different fields within those tables
i have an information table that has the following fields in it; 我有一个信息表,其中包含以下字段;
id, staffMember, lineManager, description
The staffMember and lineManager fields return integer values that correspond to the id of rows within a users table which has the following columns staffMember和lineManager字段返回与user表中具有以下列的行的id相对应的整数值
id, firstname, surname
I can use the following query to return the info in my information table, substituting the staffMember value for a CONCAT of firstname and surname: 我可以使用以下查询返回信息表中的信息,将staffMember值替换为名字和姓氏的CONCAT:
SELECT information.id,
CONCAT( users.firstname, ' ', users.surname ) AS staffMember,
information.lineManager,
LEFT(information.description,200) As description
FROM information
LEFT JOIN users
ON ( information.staffMember = users.id )
LIMIT 0 , 30"
But what i want to be able to do, is repeat the process that's working on the value of staffMember on lineManager as well in the same query (which i then pass as a json string) - however, i know i can't have two LEFT joins to the same table but equating different fields. 但我想要做的是重复在lineManager上的staffMember的值以及相同的查询(我然后作为json字符串传递)的过程 - 但是,我知道我不能有两个LEFT连接到同一个表,但等同于不同的字段。
Any help would be gratefully received. 我们将非常感激地提供任何帮助。
It sounds like you want this: 听起来你想要这个:
SELECT i.id,
CONCAT(u1.firstname, ' ', u1.surname) AS staffMember,
CONCAT(u2.firstname, ' ', u2.surname AS lineManager,
LEFT(i.description,200) As description
FROM information i
LEFT JOIN users u1
ON i.staffMember = u1.id
LEFT JOIN users u2
on i.lineManager = u2.id
LIMIT 0 , 30
You just perform a LEFT JOIN
on the users
table twice. 您只需在users
表上执行两次LEFT JOIN
。 Once you will join on the staffMember
and the other time you will join on lineManager
. 一旦您加入staffMember
,另一次您将加入lineManager
。 By providing a different table alias to the table you can distinguish between the tables and the values. 通过为表提供不同的表别名,您可以区分表和值。
Of if you want to be clearer: 如果你想更清楚:
SELECT i.id,
CONCAT(staff.firstname, ' ', staff.surname) AS staffMember,
CONCAT(manager.firstname, ' ', manager.surname AS lineManager,
LEFT(i.description,200) As description
FROM information i
LEFT JOIN users staff
ON i.staffMember = staff.id
LEFT JOIN users manager
on i.lineManager = manager.id
LIMIT 0 , 30
Something like this: 像这样的东西:
SELECT information.id FROM information
LEFT JOIN users u ON u.id = information.staffMember
LEFT JOIN users ul ON ul.id = information.lineManager
The letters/words after the table are completely made up by you. 桌子后面的字母/单词完全由你完成。 They are aliases for the table name that you make up on the fly. 它们是您动态组成的表名的别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.