[英]Updating a sql table with new column
I am using mysql and I have a table with columns: postid, userid, datestamp 我使用的是mysql,我有一个包含列的表:postid,userid,datestamp
I want to create a new column called 'entry' that numbers the entries chronologically according to datestamp 我想创建一个名为“entry”的新列,该列根据datestamp按时间顺序对条目进行编号
So, for the rows: 所以,对于行:
3705 1 2003-12-08 13:42:13
3711 15 2003-11-12 15:22:01
3701 2 2004-01-11 01:22:12
I want to end up with: 我想最终得到:
3705 1 2003-12-08 13:42:13 2
3711 15 2003-11-12 15:22:01 1
3701 2 2004-01-11 01:22:12 3
How can I perform this task? 我该如何执行此任务?
ALTER TABLE tbl ADD COLUMN nr integer;
SET @rn := 0;
UPDATE tbl
SET rn = (@rn := @rn + 1)
ORDER BY datestamp, postid, userid;
Here is a working demo . 这是一个工作演示 。
I took the substitute for the missing window function row_number()
in MySQL from @OMG Ponies' Posting . 我从@OMG小马的发布中取代了MySQL中缺少的窗口函数row_number()
。
Sort by postid
and userid
in addition to datestamp
as the timestamp column is not guaranteed to be unique. 除了datestamp
之外,还可以使用postid
和userid
进行排序,因为时间戳列不保证是唯一的。
Read about setting variables in the manual . 请阅读手册中有关设置变量的内容 。
ALTER TABLE tbl ADD COLUMN entry INTEGER
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
For setting it to the ordered number you would use RANK function but MySQL doesn't have one, so will have to look for substitutes like this one: http://thinkdiff.net/mysql/how-to-get-rank-using-mysql-query/ 要将它设置为有序数字,你将使用RANK函数,但MySQL没有,所以必须寻找像这样的替代品: http : //thinkdiff.net/mysql/how-to-get-rank-using -mysql查询/
If you want just to order chronologically the dates you dont have to create another column. 如果您只想按时间顺序订购您没有创建另一列的日期。 You can do it with a simple cursor. 你可以用一个简单的光标做到这一点。
private static String[] FROM = {_ID, COL_1, COL_NAME, COL_2, COL_3, COL_4}; //add your columns
private static String ORDER_BY = COL_NAME + " DESC"; //or ASC for ascending
Cursor cursor = db.query(DATABASE_TABLE, FROM, null, null, null, null, ORDER_BY);
and then just show the results from the cursor 然后只显示光标的结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.