MySQL:按组值添加ID

时间:2015-08-20 14:40:12

标签: mysql grouping

假设我有一张myTable这样的表:

col1   | col 2
-------+---------
213    | Peach
32467  | Peach
44     | Apple
5      | Banana!
3      | Banana!

如何添加id列以获得如下结果:

col1   | col 2   | id
-------+---------+------
213    | Peach   | 1
32467  | Peach   | 1
44     | Apple   | 2
5      | Banana! | 3
3      | Banana! | 3

col 2可以包含任何值...

2 个答案:

答案 0 :(得分:0)

有没有比做

更好的方法
SELECT `col 1`, `col 2`, groupID
FROM `myTable` as a, 
(SELECT `col 2`, @groupID := ifnull(@groupID,0) + 1 as groupID 
FROM myTable
GROUP by 1) as b
ON a.`col 2` = b.`col 2`

答案 1 :(得分:0)

首先,您可以使用此查询为每个组分配ID:

SET @i = 0;
SELECT DISTINCT col2, (@i:= @i+1) as id FROM `myTable`

你会得到类似的东西:

| col2    | id |
+---------+----|
| Peach   | 1  |
| Apple   | 2  |
| Banana! | 3  |

然后你可以将这个子查询加入到你的桌子上' col2':

SET @i = 0;
SELECT a.*, b.id from `myTable` as a
INNER JOIN (
    SELECT DISTINCT col2, (@i:= @i+1) as id FROM `myTable`
) b ON a.col2 = b.col2

你会得到你需要的东西。当然,ifnull()函数允许避免使用SET语句。

但是,您确定需要此id列吗?如果你没有将它存储在表格中,那么根本不需要它。