![](/img/trans.png)
[英]How to update a field of a table by using data from another table(MYSQL)
[英]mysql update table using data from another table
我在数据库中有一个这样的表结构:
/*city*/
+----------+------------+
| id | name |
|-----------------------|
| 1 | Gotham |
| 2 | Metropolis |
| 3 | Smallville |
| 4 | Fawcett |
+----------+------------+
/*district*/
+----------+------------+------------+
| id | name | city_id |
|------------------------------------|
| 1 | A | 1 |
| 2 | B | 1 |
| 3 | C | 2 |
| 4 | D | 2 |
| 5 | E | 2 |
| 6 | F | 3 |
| 7 | G | 3 |
| 8 | H | 4 |
+----------+------------+------------+
/*distance*/
+----------+-------------+------------------+-------------------------+---------+
| id | origin_city | city_destination | district_destination | length |
|---------------------------------------------------------------------|---------|
| 1 | 2 | 2 | 1 | 4 |
| 2 | 3 | 3 | 1 | 5 |
| 3 | 1 | 1 | 2 | 6 |
| 4 | 2 | 2 | 3 | 5 |
| 5 | 4 | 4 | 1 | 8 |
| 6 | 4 | 2 | 4 | 9 |
| 7 | 4 | 3 | 5 | 11 |
| 8 | 1 | 4 | 6 | 13 |
+----------+-------------+------------------+-------------------------+---------+
表区通过city_id外键连接到城市表,而距离表同时连接到城市表和区表,问题是如果在距离表中,有错误的city_destination数据与district_destination不匹配,我需要解决此问题,但我不知道如何使用更新查询来解决此类问题,以显示错误的city_destination数据,我使用了以下查询:
SELECT a.* FROM distance a, district b WHERE a.district_destination = b.id AND a.city_destination != b.city_id
首先,放弃老式的逗号语法进行联接操作。 使用JOIN
关键字并将连接谓词移至ON
子句。 编写一个SELECT查询,该查询返回要更新的现有行(连同PK和要分配的新值。(看起来就到您为止)。
假设我们要替换distance
表的city_destination
列中的值,并且看到此列在功能上取决于district_destination
...
从查询开始,该查询返回要更新的行。
SELECT ce.id AS id
, ce.district_destination AS district_destination
, ce.city_destination AS old_city_destination
, ct.city_id AS new_city_destination
FROM distance ce
JOIN district ct
ON ct.id = ce.district_destination
AND NOT ( ct.city_id <=> ce.city_destination )
ORDER BY ce.id
在MySQL中,多表更新非常简单。 该语法记录在《 MySQL参考手册》中。
首先,我们将之前的查询作为内联视图将其编写为SELECT
SELECT t.id
, s.new_city_destination
FROM ( SELECT ce.id AS id
, ce.district_destination AS district_destination
, ce.city_destination AS old_city_destination
, ct.city_id AS new_city_destination
FROM distance ce
JOIN district ct
ON ct.id = ce.district_destination
AND NOT ( ct.city_id <=> ce.city_destination )
ORDER BY ce.id
) s
JOIN distance t
ON t.id = s.id
然后,我们可以将其转换为UPDATE语句。 用UPDATE
替换SELECT ... FROM
并在末尾添加SET
子句。 (在WHERE
子句之前,如果有一个。)
UPDATE ( SELECT ce.id AS id
, ce.district_destination AS district_destination
, ce.city_destination AS old_city_destination
, ct.city_id AS new_city_destination
FROM distance ce
JOIN district ct
ON ct.id = ce.district_destination
AND NOT ( ct.city_id <=> ce.city_destination )
ORDER BY ce.id
) s
JOIN distance t
ON t.id = s.id
SET t.city_destination = s.new_city_destination
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.