在给定条件的情况下连接2列

时间:2012-11-15 13:23:54

标签: mysql

我有以下情况:我有一个表可以说X字段是

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

我仅在city相同且city不同时才尝试更新country列。我试过做

  

UPDATE X SET(City)= CONCAT(CITYCOUNTRY)WHERE =?

where where子句应该是什么?

修改

输出应该看起来像

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

4 个答案:

答案 0 :(得分: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不允许您更新表。

答案 1 :(得分: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 
    )

答案 2 :(得分: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

现在我们必须将所有数据都推送到临时表中,因为当您在更新同一个表时尝试使用嵌套表select时,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);

答案 3 :(得分:0)

尝试使用:

GROUP_CONCAT()

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

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