MySQL同表两次左连接需求:将请求表ID转换为用户名
Create View to Replace User IDs with Usernames
To get the view you want—where Updatedby and Createdby show usernames instead of IDs—you’ll need to join the requests table with the users table twice (once for each user ID field) using table aliases to avoid confusion. Here’s the SQL to create the view:
CREATE VIEW request_details AS SELECT r.ID, u_updated.Name AS Updatedby, u_created.Name AS Createdby, r.DateCreated, r.DateUpdated FROM requests r INNER JOIN users u_updated ON r.Updatedby = u_updated.ID INNER JOIN users u_created ON r.Createdby = u_created.ID;
Quick breakdown of how this works:
- View creation:
CREATE VIEW request_details ASsets up a reusable view (feel free to renamerequest_detailsto something more fitting for your workflow). - Table aliases:
rshortensrequests,u_updatedrefers to the user who updated the request, andu_createdrefers to the user who created it. This lets us join the sameuserstable twice without column name conflicts. - Joins:
INNER JOINensures we only include requests where both the update and create user IDs exist in theuserstable. If you might have requests with missing user IDs (and want to showNULLinstead of excluding those rows), swapINNER JOINwithLEFT JOIN. - Column mapping: We pull the
Namefrom each joined user record and label them asUpdatedbyandCreatedbyto match your desired output.
Once you run this, querying SELECT * FROM request_details; will return exactly the format you’re after:
| ID | Updatedby | Createdby | DateCreated | DateUpdated |
|---|---|---|---|---|
| 1 | John | Sara | 10/12/2017 | 21/01/2018 |
| 2 | John | John | 11/12/2017 | 22/01/2018 |
| 3 | John | Pete | 12/12/2017 | 23/01/2018 |
| 4 | Sara | Sara | 13/12/2017 | 24/01/2018 |
Content of the question originates from Stack Exchange, question author John Pham.
相关产品推荐
相关产品推荐

