繁体   English   中英

MySQL将数据从一个表插入到另一个选定的行

[英]Mysql insert data from one table to another selected rows

嗨,我有2个表的Mysql db第一个表有2个字段

country_codecity_name

第二个表有3个字段

country_codecountry_namecountry_cities

我需要创建一个查询:

select all city_name and country_code from first table and for each country_code insert into second table in field country_cities

在第一张桌子上找到的城市用逗号分隔

我不确定我是否可以使用Mysql查询或最好使用PHP脚本感谢您的帮助

您可以使用第一个表中的城市列表来更新第二个表中的city_name列。 如果第一个表的城市名称已经用逗号分隔,则只需将其从一个表移动到另一个表即可。

UPDATE second_table 
SET S.country_cities = A.city_name
FROM first table A INNER JOIN second_table S 
ON A.country_code = S.country_code

如果您需要在second_table更新country_cities ,则可以通过以下示例查询来完成:

UPDATE second_table st
INNER JOIN (
    SELECT 
    country_code,
    GROUP_CONCAT(city_name) as grouped_cities
    FROM first_table
    GROUP BY country_code
) as tmp_table ON tmp_table.country_code = st.country_code
SET st.country_cities = tmp_table.grouped_cities;

在这里您可以找到GROUP_CONCAT文档。 只是复制和粘贴,以避免对分隔符造成混淆:

组中值之间的默认分隔符是逗号(“,”)。 要明确指定分隔符,请使用SEPARATOR,后跟应该在组值之间插入的字符串文字值。 要完全消除分隔符,请指定SEPARATOR。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM