2

我有以下情况:我有一张表可以说X字段在哪里

 -------------------------
 | City      | Country   |
 ------------------------|
 | Melbourne | Australia |
 | Phoenix   | USA       |
 | Manchester| USA       |
 | Manchester| UK        |
 | Phoenix   | USA       |
 | Pune      | India     |
 ------------------------

我试图仅在相同且不同时更新city列。我试过做citycountry

UPDATE X SET ( City) = CONCAT( CITY, COUNTRY) WHERE = ?

where子句应该是什么?

编辑:

输出应该看起来像

 ------------------------------
 | City           | Country   |
 -----------------------------|
 | Melbourne      | Australia |
 | Phoenix        | USA       |
 | Manchester, USA| USA       |
 | Manchester, UK | UK        |
 | Phoenix        | USA       |
 | Pune           | India     |
 ------------------------------
4

4 回答 4

1
UPDATE X inner join X X_1 on X.city = X_1.city
SET X.City=CONCAT(X.city, ', ', X.Country)
WHERE X.country <> X_1.country

这会将城市名称设置为CONCAT(X.city, ', ', X.Country)仅在多个国家/地区存在相同城市名称的情况下。

编辑:我想我更喜欢这个其他版本:

UPDATE
  X inner join
  (select city from X group by city having count(*)>1) X_dup
  on X.city = X_dup.city
SET X.City=CONCAT(X.city, ', ', X.Country)

我正在使用所有这些奇怪的连接,因为如果您在子查询中引用它,MySql 不允许您更新表。

于 2012-11-15T13:33:49.477 回答
1
UPDATE X SET (City) = CONCAT(CITY,', ',COUNTRY) 
WHERE CITY IN 
    ( 
    SELECT tmp.City FROM 
        (SELECT DISTINCT x2.City, x2.Country FROM X AS x2) AS tmp 
    GROUP BY tmp.City HAVING COUNT(1) > 1 
    )
于 2012-11-15T13:36:42.660 回答
0

您可以City通过如下查询获取所有重复的城镇:

SELECT City, COUNT(City) AS Count
FROM X
GROUP BY City
HAVING Count > 1

IN在条件(只有一列)中最容易使用,因此将封装它:

SELECT City
FROM (
    SELECT City, COUNT(City) AS Count
    FROM X
    GROUP BY City
    HAVING Count > 1
) AS t1

现在我们必须将所有数据推送到临时表中,因为当您在更新同一个表时尝试使用嵌套表选择时 mysql 不起作用:

CREATE TEMPORARY TABLE tmp (VARCHAR(255) city);
INSERT INTO tmp (
    SELECT City
    FROM (
        SELECT City, COUNT(City) AS Count
        FROM X
        GROUP BY City
        HAVING Count > 1
    ) AS t1
)

现在我们可以启动更新:

UPDATE X SET (City) = CONCAT(CITY,COUNTRY)
WHERE `City` IN (SELECT City FROM tmp);
于 2012-11-15T13:43:02.477 回答
0

尝试使用:

GROUP_CONCAT()

返回一个字符串结果,其中包含来自组的连接的非 NULL 值

http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/

于 2012-11-15T13:44:06.920 回答