我有一个这样的表:
id name
0 Bob
1 Alice
2 Bob
3
4 Bob
5 Mary
6 Alice
我需要为每个不同的名称分配一个group_id
:
id name group_id
0 Bob 0 -- Bob's group
1 Alice 1 -- Alice's group
2 Bob 0 -- Bob's group
3 -- no group (NULL)
4 Bob 0 -- Bob's group
5 Mary 2 -- Mary's group
6 Alice 1 -- Alice's group
这可以在 MySQL 中一行完成吗?
我知道我可以找到带有自动增量列的唯一名称,然后根据名称连接回原始表 - 但我想知道是否存在更简单/更快的解决方案...
最佳答案
是的,用例。只需根据表达式添加一个新的计算列,该表达式为 name
列的每个字符串值输出适当的值
Select id, name,
case name
when 'Bob' then 0
when 'Alice' then 1
when 'Mary' then 2
-- etc.
end GroupId
From table
如果您事先不知道名称,或者名称太多,请尝试以下操作:
Select id, name,
(select count(distinct name)
from table
where name < t.Name) groupId
From table t
除非您在名称列上添加索引,否则在大型表上这将非常慢。
要为 name = null 的行输出 null 而不是 0,请使用以下命令:
Select id, name,
case when name is null then null
else (select count(distinct name)
from table
where name < t.Name) end groupId
From table t
关于mysql - SQL 中的标签组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45522198/