0

我有 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:我是个白痴。我没有正确设置我的桌子。你们都答对了!抱歉浪费您的时间!!!

4

3 回答 3

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

SQL 小提琴示例

输出

| U_ID | ID | USERNAME | ADMINUSERNAME | SECTIONNAME |
------------------------------------------------------
|   44 |  1 |    user1 |     useradmin |        Test |
于 2012-06-25T21:43:15.930 回答
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 上添加一个别名,它允许您将用户“用户”表与用户“管理员”表区分开来。

在这里,您的结果将是这种数组:[id, user_name, admin_name, section_name]

于 2012-06-25T21:43:26.090 回答
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
于 2012-06-25T21:44:37.100 回答