1

Here are two tables. I want to UPDATE (NOT to SELECT) the first table based on the info from both tables.

The first table named somecities:

Name - State - Country - Info1 - Info2
Orlando - FL - US - 123 -AAA
Hrodna - HV - BY - 890 -BBB

The second table named allcities:

Name - State - Country - Info1
Orlando - FL - US - 123
Orlando - KY - US - 456
Orlando - WV - US - 789
Orlando - SW - SA - 333
Hrodna - HV - BY - 890
Minsk - MV - BY - 199

Any pair of (Name, State, Country) from somecities table is in the allcities table, if it matters. So, the allcities table is bigger.

I want to modify somecities this way:

1)take the first row, take Orlando. It is met 4 times in allcities. So, make 4 strings of Orlando instead of one (add 3 rows to somecities).

2) Take the next city (the second and the last one) - Hrodna. Hrodna is met only one time in allcities so we do not add any rows (add zero rows) to somecities.

3) Do it for each row in somecities.

The result of the query is the updated somecities:

Name - State - Country - Info1 - Info2
Orlando - FL -  US     - 123   -  AAA
Orlando - KY -  US     - 456   -  AAA
Orlando - WV -  US     - 789   -  AAA
Orlando - SW -  SA     - 333   -  AAA
Hrodna  - HV -  BY     - 890   -  BBB

P.S. As you can see, the values in the Info2 are taken from Info2 for the same city.

Can it be done in one query? Two queries as an answer will be accepted as well.

Did I explain it clear?

Thank you.

4

2 回答 2

2

你需要一个 INSERT 查询,你可以使用这样的东西:

INSERT INTO somecities
SELECT a.*, si.Info2
FROM
  allcities a LEFT JOIN somecities s
  ON a.Name=s.Name AND a.State=s.State AND a.Country=s.Country
  INNER JOIN (SELECT DISTINCT Name, Info2
              FROM somecities) si
  ON a.Name=si.Name
WHERE
  s.Name IS NULL

在此处查看小提琴。

这将插入一些城市中不存在的所有城市中的所有行(或者具有相同名称但不同的州或国家/地区),因为我正在使用带有 WHERE s.Name IS NULL 的 LEFT JOIN。

然后,我选择了某些城市中存在的城市名称和 Info2 列,并且我只对名称进行了 INNER JOIN,以便仅返回存在于某些城市中的行至少一次。

于 2013-10-30T22:55:25.333 回答
1

您可以用于NOT EXISTS测试尚未在表中的记录,然后进行快速连接以从现有记录中获取 info2:

SQL Fiddle 演示

INSERT INTO somecities (Name,State,Country,Info1, Info2)
SELECT data.Name,data.State,data.Country,data.Info1,inf.Info2
FROM (
    SELECT *
    FROM allcities a
    WHERE NOT EXISTS (SELECT * 
                      FROM somecities s 
                      WHERE s.name = a.name
                            AND s.state = a.state
                            AND s.country = a.country
                            AND s.info1 = a.info1
                     )
  ) data
  INNER JOIN (SELECT DISTINCT Name, Info2 FROM somecities) inf
    ON data.name = inf.name;

我个人觉得它更容易阅读EXISTSNOT EXISTS而不是大量的连接,但这是个人喜好,请自行选择。

于 2013-10-30T23:07:49.580 回答