I have a select in mysql table that results this:

我在mysql表中有一个select,结果如下:

topic user weight  
"hello" 324  3  
"hello" 21   1  
"second thread" 34 1  
"second thread" 21 1  
"second thread" 32 1  
"second thread" 3  3  
"hello" 23   1  

I would like to turn the first column "topic" into numbers, to simplify things. Is it possible to turn just one column into numbers like this:

我想把第一列“主题”变成数字,以简化事情。是否可以将一列转换为如下数字:

topic user weight  
1     324  3  
1     21   1  
2     34   1  
2     21   1  
2     32   1  
2      3   3  
1     23   1  

Many thanks for your help!

非常感谢您的帮助!

Best regards, Simone

最好的问候,西蒙娜

3 个解决方案

#1


1

Here's a method which gets a DISTINCT list of topics and assigns row numbers to join against. This makes it possible to do in one query, plus a variable:

这是一个获取DISTINCT主题列表并指定要加入的行号的方法。这使得可以在一个查询中加上一个变量:

Edited: Refactored to initialize the rownum variable in the FROM clause, which is a little tidier looking and won't produce n*2 values for the row numbers.

编辑:重构初始化FROM子句中的rownum变量,这看起来有点整洁,并且不会为行号生成n * 2值。

SELECT id, yourtable.*
FROM 
  yourtable
  JOIN (
    /* Suquery gets row rank per distinct topic */
    SELECT topic, @rownum:=@rownum+1 AS id
    FROM (
      /* Variable initialized in FROM clause */
      SELECT @rownum:=0
    ) sr JOIN (
      SELECT DISTINCT topic FROM yourtable
    ) t
  ) topicids ON yourtable.topic = topicids.topic

http://sqlfiddle.com/#!2/58d53/14

ID  TOPIC    USER   WEIGHT
1   "hello"  324    3
1   "hello"  21     1
2   "second" 34     1
2   "second" 21     1
2   "second" 32     1
2   "second" 3      3
1   "hello"  23     1

更多相关文章

  1. 查询表中的某一行,表中没有行号相关的属性字段,SQL语句怎么写啊?50

随机推荐

  1. 【066】Android & Java 难点解析
  2. Android Camera调用流程
  3. Android修改gen下包名
  4. Android: Android Wifi System
  5. android WebView loadData不能解析
  6. 本博博文预报
  7. 如何去写 Android(安卓)init.rc (Android
  8. 开启 Android 反射调用
  9. Android MediaController
  10. 通过JS或PHP检测Android