3

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

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  

我想将第一列“主题”变成数字,以简化事情。是否可以将一列变成这样的数字:

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

非常感谢您的帮助!

最好的问候,西蒙娜

4

3 回答 3

1

也许使用临时表?

CREATE TABLE temp2 (
  id int AUTO_INCREMENT PRIMARY KEY,
  topic varchar(20));

INSERT INTO temp2 (topic)
SELECT DISTINCT topic FROM temp;

SELECT b.id, a.user, a.weight
FROM temp a
INNER JOIN temp2 b ON b.topic = a.topic

结果

| 身份证 | 用户 | 重量 |
----------------------
| 1 | 324 | 3 |
| 1 | 21 | 1 |
| 2 | 34 | 1 |
| 2 | 21 | 1 |
| 2 | 32 | 1 |
| 2 | 3 | 3 |
| 1 | 23 | 1 |

查看演示

于 2013-02-11T17:57:07.197 回答
1

这是一种获取DISTINCT主题列表并分配要加入的行号的方法。这使得在一个查询中加上一个变量成为可能:

编辑:重构以初始化子句rownum中的变量FROM,这看起来更整洁,并且不会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
于 2013-02-11T17:58:36.453 回答
0

你也可以试试

SELECT
   topic, 
   (SELECT COUNT(topic) FROM yourtable where topic = outer_table.topic),
   user, 
   weight  
FROM 
   yourtable  outer_table
于 2013-02-11T18:02:06.597 回答