我有3张桌子。
users
------------
id | Name |
------------
44 | user1 |
45 |useradmin|
Sections
------------
id | Name
------------
1 | Test |
Assigns
------------
id | u_id | section_id | admin_u_id
-----------------------------------
1 | 44 | 1 | 45 |
我试图提取Assigns
表并将u_id和admin_u_id替换为相应的用户名,将section_id替换为部分名称。
到目前为止我所拥有的:
SELECT Assigns.u_id, Assigns.id, users.id,users.id
FROM Assigns
INNER JOIN users
ON Assigns.u_id=users.id
INNER JOIN users
ON Assigns.admin_u_id=users.id
INNER JOIN Sections
ON Assigns.section_id=Sections.id
让我失望的是选择线。我希望它以不同的值显示两次users.id。
非常感谢任何帮助或推动正确的方向。
感谢!!!
编辑: 以下是实际的表名。
我的MYSQL查询中没有任何错误,只返回一个空集
SELECT mrfv0_codes_assign.u_id, mrfv0_codes_assign.id, u1.id,u2.id
FROM mrfv0_codes_assign
INNER JOIN mrfv0_users u1 ON mrfv0_codes_assign.u_id=u1.id
INNER JOIN mrfv0_users u2 ON mrfv0_codes_assign.admin_u_id=u2.id
INNER JOIN mrfv0_codes_sections ON mrfv0_codes_assign.section_id=mrfv0_codes_sections.id
EDIT2: 我是一个白痴。我没有正确地摆好桌子。你们都有正确的答案! 抱歉浪费你的时间!!!
答案 0 :(得分:2)
SELECT a.u_id,
a.id,
u1.name AS Username,
u2.name AS AdminUsername,
s.name AS SectionName
FROM mrfv0_codes_assign a
INNER JOIN mrfv0_users u1 ON a.u_id = u1.id
INNER JOIN mrfv0_users u2 ON a.admin_u_id = u2.id
INNER JOIN mrfv0_codes_sections s ON a.section_id = s.id
<强>输出强>
| U_ID | ID | USERNAME | ADMINUSERNAME | SECTIONNAME |
------------------------------------------------------
| 44 | 1 | user1 | useradmin | Test |
答案 1 :(得分:1)
SELECT Assigns.id AS id,
users.name AS user_name,
admins.name AS admin_name,
Sections.name AS section_name
FROM Assigns
INNER JOIN users ON Assigns.u_id = users.id
INNER JOIN users AS admins ON Assigns.admin_u_id = admins.id
INNER JOIN Sections ON Assigns.section_id=Sections.id
只需在INNER JOIN上添加一个别名,它允许您从用户“admin”表中区分用户“user”表。
在这里,您的结果将是这种数组:[id, user_name, admin_name, section_name]
答案 2 :(得分:1)
尝试为表分配别名。例如:
SELECT Assigns.u_id, Assigns.id, u1.id,u2.id
FROM Assigns
INNER JOIN users u1
ON Assigns.u_id=u1.id
INNER JOIN users u2
ON Assigns.admin_u_id=u2.id
INNER JOIN Sections
ON Assigns.section_id=Sections.id