[英]MySQL: Update column of multiple rows based on another row
I have a database of Tweets with the following columns 我有带有以下各列的推文数据库
+------------------------+--------------+
| Field | Type |
+------------------------+--------------+
| id | varchar(128) |
| message_id | bigint(20) |
| message | text |
| from_id | int(12) |
| cnty | int(5) |
| county | varchar(64) |
| city | varchar(64) |
| state | varchar(2) |
+------------------------+--------------+
The database contains multiple messages for each distinct from_id
. 该数据库为每个不同的
from_id
包含多个消息。 There is one row for each from_id
that contains cnty
, county
, city
. 每个
from_id
都有from_id
,其中包含cnty
, county
, city
。 and state
and all other rows with the same from_id
have NULL values for those columns. 并且
state
和所有其他具有相同from_id
行的这些列具有NULL值。 I would like to fill them in with the same values for each from_id
. 我想为每个
from_id
用相同的值填充它们。 Is this possible in MySQL? 这在MySQL中可能吗? My first thought was to write a Python script to do this, but maybe that is overkill.
我的第一个念头是编写一个Python脚本来执行此操作,但这也许太过分了。
You could use a subquery that gets all non null values, then use an UPDATE query with a join: 您可以使用获取所有非空值的子查询,然后使用具有联接的UPDATE查询:
UPDATE
tweets INNER JOIN (
SELECT from_id, MAX(cnty) AS cnty, MAX(country) AS country, MAX(city) AS city, ...
FROM tweets
GROUP BY from_id) m
ON tweets.from_id = m.from_id
SET
tweets.cnty=m.cnty,
tweets.country=m.country,
tweets.city=m.city,
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.