mysql 递归更新

标签 mysql recursive-query sql-update

我有两个 mysql 表,一个包含汽车的详细信息,另一个包含汽车的所有可能型号,如下所示:

cars:
  car_id
  model
  [more details]

models:
  model_id
  model_name

现在,我的问题是“cars”表中存储的模型详细信息是 model_name,而不是我想要的 model_id

我猜我需要某种递归更新表才能更新 cars.model,但我的大脑停止了工作,不知道该怎么做。有人对如何做到这一点有任何提示吗?

感谢任何可以提供帮助的人!

最佳答案

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)

关于mysql 递归更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/280491/

相关文章:

python - 使用 django 在 mysql 数据库上使用 DISTINCT

php - 在mysqli中调用两个存储过程导致 'Commands out of sync'错误

mysql - 结合 select 和 update mysql 查询来获取计数

mysql - 如何将mysql日期列的现有内容批量移动到不同类型的新内容?

mysql - 如何创建MySQL分层递归查询

mysql - 用另一个表中的数据更新 mysql 表

php - 在 Codeigniter 中选择并加入同一个表

mysql - 解析 web.config 时出现配置错误

sql - DB2 中的 SQL 递归连接问题

sql - PostgreSQL 有效地找到线性列表中的最后一个后代