2008-11-11 70 views
0

我有兩個MySQL表,一個包含在汽車的細節和一個包含汽車的所有可能的模型,例如:MySQL的遞歸更新

 
cars: 
    car_id 
    model 
    [more details] 

models: 
    model_id 
    model_name 

現在,我的問題是,存儲在該模型的細節'汽車'表是model_name,而不是model_id這是我想要的

我猜我需要某種遞歸更新表能夠更新cars.model,但我的大腦停止工作,可以'不知道該怎麼做。有沒有人有關於如何做到這一點的提示?

感謝任何人誰可以幫助!

+0

你只是問如何正確使用'模型id'字段填充'汽車'表或其他?目前尚不清楚。 – Alnitak 2008-11-11 10:16:50

回答

1
 
mysql> create table cars(car_id int auto_increment primary key, model 
varchar(50), model_id int); 
Query OK, 0 rows affected (0.01 sec) 

mysql> create table models(model_id int auto_increment primary key, name 
varchar(50)); 
Query OK, 0 rows affected (0.01 sec) 

mysql> insert into models(name) VALUES ('Taurus'), ('Ka'), ('Mustang'); 
Query OK, 3 rows affected (0.00 sec) 
Records: 3 Duplicates: 0 Warnings: 0 

mysql> insert into cars(model) VALUES ('Ka'), ('Mustang'), ('Taurus'), 
('F150'); 
Query OK, 4 rows affected (0.00 sec) 
Records: 4 Duplicates: 0 Warnings: 0 

mysql> select * from cars; 
+--------+---------+----------+ 
| car_id | model | model_id | 
+--------+---------+----------+ 
|  1 | Ka  |  NULL | 
|  2 | Mustang |  NULL | 
|  3 | Taurus |  NULL | 
|  4 | F150 |  NULL | 
+--------+---------+----------+ 
4 rows in set (0.00 sec) 

mysql> select * from models; 
+----------+---------+ 
| model_id | name | 
+----------+---------+ 
|  1 | Taurus | 
|  2 | Ka  | 
|  3 | Mustang | 
+----------+---------+ 
3 rows in set (0.00 sec) 

mysql> update cars,models set cars.model_id = models.model_id 
where models.name = cars.model; 
Query OK, 3 rows affected (0.06 sec) 
Rows matched: 3 Changed: 3 Warnings: 0 

mysql> select * from cars; 
+--------+---------+----------+ 
| car_id | model | model_id | 
+--------+---------+----------+ 
|  1 | Ka  |  2 | 
|  2 | Mustang |  3 | 
|  3 | Taurus |  1 | 
|  4 | F150 |  NULL | 
+--------+---------+----------+ 
4 rows in set (0.03 sec)