MySQL插入重复的单词到列的数量

时间:2013-09-22 19:44:54

标签: php mysql sql

我有一个包含重复单词的表和一个以“num”命名的空字段。

+----+--------------+-----+
| id | words        | num |
+----+--------------+-----+
| 1  | red          |     |
+----+--------------+-----+
| 2  | blue         |     |
+----+--------------+-----+
| 3  | red          |     |
+----+--------------+-----+
| 4  | red          |     |
+----+--------------+-----+
| 5  | blue         |     |
+----+--------------+-----+

我想在num字段中插入重复单词的数量,如下所示:

+----+--------------+-----+
| id | words        | num |
+----+--------------+-----+
| 1  | red          | 1   |
+----+--------------+-----+
| 2  | blue         | 1   |
+----+--------------+-----+
| 3  | red          | 2   |
+----+--------------+-----+
| 4  | red          | 3   |
+----+--------------+-----+
| 5  | blue         | 2   |
+----+--------------+-----+

我怎么能通过php或sql做到这一点?

3 个答案:

答案 0 :(得分:5)

这是MySQL

您可以加入子查询,该子查询根据使用相关子查询的words在每IDUPDATE tableName a INNER JOIN ( SELECT a.id, ( SELECT COUNT(*) FROM tableName c WHERE c.words = a.words AND c.id <= a.id ) AS RowNumber FROM TableName a ) b ON a.id = b.id SET a.num = b.rownumber 生成一个rownumber。

{{1}}

答案 1 :(得分:1)

这样的事情是实现它的简单方法:

CREATE TABLE tmp_colors ( 
   id int auto_increment primary key,
   word varchar(16) NOT NULL
);

INSERT INTO tmp_colors SELECT words FROM table GROUP BY words;

UPDATE table t1 JOIN tmp_colors t2 ON t2.word = t1.words SET t1.num = t2.id;

答案 2 :(得分:0)

如果DBMS支持窗口功能(如Oracle或MS SQL Server):

select id,word,row_number() over(partition by word order by id)
from t1 
order by id;