如何更改select语句中的列值

时间:2013-02-11 17:50:44

标签: mysql sql

我在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  

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

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

非常感谢你的帮助!

祝你好运, 西蒙

3 个答案:

答案 0 :(得分: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

<强>结果

| ID | USER | WEIGHT |
----------------------
|  1 |  324 |      3 |
|  1 |   21 |      1 |
|  2 |   34 |      1 |
|  2 |   21 |      1 |
|  2 |   32 |      1 |
|  2 |    3 |      3 |
|  1 |   23 |      1 |

See the demo

答案 1 :(得分: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 个值行号。

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

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

{{1}}

答案 2 :(得分:0)

您也可以尝试

SELECT
   topic, 
   (SELECT COUNT(topic) FROM yourtable where topic = outer_table.topic),
   user, 
   weight  
FROM 
   yourtable  outer_table