4

假设我们有这样的桌子

id      |   group_id    |   TEXT    |
--------------------------------------
1       |                   |   NBA
--------------------------------------
2       |                   |   NHL
--------------------------------------
3       |                   |   NBA
--------------------------------------
4       |                   |   NHL
--------------------------------------
5       |                   |   NHL
--------------------------------------

是否可以使用在列 TEXT 中重复(重复)文本的事实使用 MySQL 函数或查询或任何东西创建 group_id :)?有一张这样的桌子

id      |   group_id    |   TEXT    |
--------------------------------------
1       |       10      |   NBA
--------------------------------------
2       |       11      |   NHL
--------------------------------------
3       |       10      |   NBA
--------------------------------------
4       |       11      |   NHL
--------------------------------------
5       |       11      |   NHL
--------------------------------------
4

3 回答 3

3

您可以尝试使用HEX功能:

SELECT id, HEX(Text) as group_id, Text
FROM Tbl

如果你想要十进制值,你可以从十六进制转换它:

SELECT id, CONV(HEX(Text), 16, 10) as group_id, Text
FROM Tbl

结果:

ID  GROUP_ID    TEXT
1   5128769 NBA
2   5128769 NBA
3   5130316 NHL
4   5130312 NHH
5   5130316 NHL
8   4342081 BAA
9   4342081 BAA

SQLFiddle

于 2013-08-01T05:41:24.290 回答
1
CREATE TEMPORARY TABLE nums (n int AUTO_INCREMENT PRIMARY KEY, txt varchar(4)) AUTO_INCREMENT=10;
INSERT INTO nums (txt) SELECT DISTINCT text FROM table1;
UPDATE table1 INNER JOIN nums ON txt=text SET group_id=n 

SQLfiddle

于 2013-08-01T05:55:12.143 回答
1

看着我的旧答案,我只是想到了另一种在没有 tmp 表的情况下解决问题的方法:

CREATE Table tbl (id int,grpid int, text varchar(10));
INSERT INTO tbl (id,text) VALUES (1,'NBA'),(2,'NBA'),
   (3,'NHL'),(4,'NHH'),(5,'NHL'),(8,'BAA'),(9,'BAA');

SET @i:=100; -- set the start sequence number for grpid
UPDATE tbl INNER JOIN ( 
SELECT @i:=@i+1 gid,text FROM (
 SELECT DISTINCT text FROM tbl ORDER BY text ) dt ) gi
ON tbl.text=gi.text 
SET tbl.grpid=gi.gid;

tbl 之后UPDATE

| ID | GRPID | TEXT |
---------------------
|  1 |   102 |  NBA |
|  2 |   102 |  NBA |
|  3 |   104 |  NHL |
|  4 |   103 |  NHH |
|  5 |   104 |  NHL |
|  8 |   101 |  BAA |
|  9 |   101 |  BAA |

sqlfiddle

于 2013-08-11T08:38:28.450 回答