将Projects表Employee列的ID替换为People表对应员工姓名
解决Projects表员工ID替换为姓名的问题
Hey there! Let's tackle this problem step by step. You need to map the numeric Employee IDs in the Projects table to the actual names from the People table, right? First, let's recap your table structures and data clearly:
原表结构与数据
People表
| ID | Employee |
|---|---|
| 1 | Saul |
| 2 | Jess |
| 3 | Kenny |
Projects表
| ID | Project | Employee |
|---|---|---|
| 1 | pro1 | 3 |
| 2 | pro2 | 1 |
| 3 | pro3 | 2 |
I'll cover two common scenarios for you below:
场景1:查询时显示姓名(不修改原表)
If you just want to see employee names in your query results without altering the original Projects table, using a JOIN to link the two tables is the way to go:
SELECT p.ID, p.Project, pe.Employee AS EmployeeName FROM Projects p JOIN People pe ON p.Employee = pe.ID;
说明:
- The
JOINclause matches the numericEmployeeID in Projects to theIDcolumn in People, pulling in the corresponding name. - Your query result will look like this:
| ID | Project | EmployeeName |
|---|---|---|
| 1 | pro1 | Kenny |
| 2 | pro2 | Saul |
| 3 | pro3 | Jess |
场景2:永久更新Projects表的Employee列
If you need to permanently replace the numeric IDs in Projects' Employee column with names, use an UPDATE ... JOIN statement. Important: Back up your data first! Updates are irreversible if something goes wrong.
MySQL/MariaDB写法:
UPDATE Projects p JOIN People pe ON p.Employee = pe.ID SET p.Employee = pe.Employee;
PostgreSQL写法(PostgreSQL doesn't support direct UPDATE JOIN, so use this alternative):
UPDATE Projects SET Employee = pe.Employee FROM People pe WHERE Projects.Employee = pe.ID::TEXT; -- Note: If Projects.Employee is an integer type, you'll need to convert it to TEXT first to store the name string.
关键注意点:
- Before running the update, run the query from Scenario 1 to double-check that all IDs match correctly—this avoids mismatched names.
- If your Projects table's
Employeecolumn is an integer type, you'll need to change it to a string type first (likeVARCHAR) to store names. Here's how to do that in MySQL:
ALTER TABLE Projects MODIFY COLUMN Employee VARCHAR(50);
内容的提问来源于stack exchange,提问作者myrtillo bruh
相关产品推荐
相关产品推荐

