我有三個表:年,員工,職位。假設我已經在這些表中有這些數據。如何複製數據庫記錄並跟蹤其新ID
years:
----------------
| id | name |
----------------
| 1 | 2011 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
---------------------------------------------------------
========================================
年表是一箇中心點。 如果我插入新的年份記錄,我還必須複製與上一年相關的所有職位和員工。
所以,如果我插入2012年入裏表,數據被假設是這樣的:
years:
----------------
| id | name |
----------------
| 1 | 2011 |
| 2 | 2012 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
| 3 | Director | 2 |
| 4 | Manager | 2 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
| 3 | Employee A (Director) | 3 (?) | 2 |
| 4 | Employee B (Manager) | 4 (?) | 2 |
---------------------------------------------------------
注意employees
表的第三和第四行中的問號。
我使用這些查詢在新的一年中插入和複製所有相關的職位和員工:
// Insert new year record
INSERT INTO years (name) VALUES (2012);
// Get last inserted year ID
$inserted_year_id = .......... // skipped
// Copy positions
INSERT INTO positions (name, year_id) SELECT name, $inserted_year_id AS last_year_id FROM positions WHERE year_id = 1;
// Copy employees
INSERT INTO employees (name, position_id, year_id) SELECT name, position_id, $inserted_year_id AS last_year_id FROM employees WHERE year_id = 1;
的問題是在複製的員工查詢。我無法找到獲取或跟蹤職位新ID的方法。
有沒有一個簡單的方法來做到這一點?
非常感謝。
您是否可以選擇更改表格結構?看起來你沒有正常形式,這可能是這裏複雜的一部分。 – andes
是的,我可以改變表格結構。 –