假设我有以下内容:
表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”只是一个基于唯一国家/地区名称的唯一编号。
使用光标很慢。我如何做到这样我可以做某种“分组”?为每个国家/地区分配唯一标识符?或者没有必要分组?
答案 0 :(得分: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
要正确地做事,
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
答案 1 :(得分:1)
您应创建一个单独的表来存储国家/地区,然后将国家/地区的主键(country_id)存储为当前表中的外键。