1

假设我有以下内容:

表A

id (auto increment primary key) | age | country
1 | 5 | Germany
2 | 6 | Spain
3 | 7 | France
4 | 7 | Spain
5 | 8 | France
6 | 9 | France
7 | 2 | Mexico
8 | 7 | Saudi Arabia
9 | 5 | Saudi Arabia

我想要结果表:

表A

id (auto increment primary key) | age | country | country_number
1 | 5 | Germany | 1
2 | 6 | Spain | 2
3 | 7 | France | 3
4 | 7 | Spain | 2
5 | 8 | France | 3
6 | 9 | France | 3
7 | 2 | Mexico | 4
8 | 7 | Saudi Arabia | 5
9 | 5 | Saudi Arabia | 5

请注意,“country_number”只是一个基于唯一国家名称的唯一编号。

使用游标很慢。我如何使它可以进行某种“分组”?为每个国家分配一个唯一标识符?还是不需要分组?

4

2 回答 2

2

查询可能是(沙特阿拉伯没有 5 个,但每个国家/地区至少有不同的 country_number)

select a.id, a.age, a.country, b.minId as country_number
FROM TableA a
INNER JOIN (SELECT MIN(id) as minId, country
            FROM TableA
            GROUP BY country) as b
      ON a.country = b.country

SqlFiddle

要把事情做好,

CREATE TABLE COUNTRY(id int PRIMARY KEY auto_increment, name VARCHAR(100))
SELECT distinct COUNTRY as name FROM TableB;

ALTER TABLE TableB Add column countryID int NOT NULL DEFAULT 0;

UPDATE TableB b, country c
set b.countryID = c.Id
where b.country = c.name;

ALTER TABLE TableB drop column country;

ALTER TABLE TableB add  FOREIGN KEY(countryID) REFERENCES country(id); 

SqlFiddle

于 2013-02-06T22:47:18.787 回答
1

您应该创建一个单独的表来存储国家/地区,然后将国家/地区的主键 (country_id) 作为外键存储在当前表中。

于 2013-02-06T22:47:16.400 回答