mysql - SQL 中的标签组

标签 mysql sql

我有一个这样的表:

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/

相关文章:

php - 如何在特定时间(计划时间)从php向android应用程序发送通知?

mysql - 使用 OR 运算符连接两个表

mysql - 如何: Sort user by values and theier new position in the table

c# - SQL 强制应用程序加密连接

mysql - 加入同一张表 2 次,然后求和 -> 将实际想要的值加倍

mysql - 如何在裸 Windows 7 安装上查看 .text 中的行终止符

mysql - 需要从具有公共(public)日期字段的 2 个表中选择所有行

sql - 为什么 COUNT(DISTINCT fieldS) 比 COUNT(DISTINCT LTRIM(RTRIM(UPPER(fieldS)))) 慢?

sql - 使用 SQL 显示零值月份

php - mySQL - 大型指标表和繁重的查询性能 - 缓存?