更新完整表格,交换列。

好的,这里是我的一个新问题。正如我在早些时候的一些问题中提到的那样,我现在正在使用 PtokaX 并在其中编写一些机器人脚本。现在我需要完全更新我的表,并交换两个特定列的值。我在一个名为 chatstats 的 MySQL 表中存储所有用户的 mainchat 计数(目前在 MyISAM 上,但正在考虑将表更改为 InnoDB)。

该表有许多行(近 1000 行),并且几乎每天都在增加。我想要做的是每周(以及每月;稍后解释)交换两列的值,并将其中一列的值设置为零。

我的表的创建语句如下:

CREATE TABLE `chatstat` (
`id` BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `username` VARCHAR(25) NOT NULL,
`totalcount` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0', `thismonth` BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
`thisweek` INT(10) UNSIGNED NOT NULL DEFAULT '0', `lastweek` INT(10) UNSIGNED NOT NULL DEFAULT '0',
`lastmonth` INT(10) UNSIGNED NOT NULL DEFAULT '0', `switched` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`), UNIQUE INDEX `id` (`id`), UNIQUE INDEX `username` (`username`)
) COLLATE='utf8_general_ci' ENGINE=MyISAM ROW_FORMAT=DEFAULT;

现在,列名是不言自明的。我创建了列 switched 来检查用户的计数是否已在该月进行了交换(通过检查是否为 1 或 0),每个星期日一次。每个星期日,我想要将 thisweek 的值与 lastweek 的值交换,并且只执行一次。目前,我的脚本如下(使用 LUA 和 PtokaX 变量):

function UpdateUserStat( con, user )
        sNick = ConvertNick( user.sNick )
        cur = assert( con:execute( string.format( [[SELECT * FROM chatstat WHERE username = '%s']], sNick ) ) )
        row = cur:fetch( {}, "a" )
        cur:close()
        if row then
                res = assert( con:execute( string.format( [[UPDATE chatstat SET totalcount = totalcount + 1 WHERE id='%d' ]], row.id ) ) )
        else
                res = assert( con:execute( string.format( [[ INSERT INTO chatstat ( username, totalcount, thismonth, thisweek ) VALUES ( '%s', 1, 1, 1 ) ]], sNick ) ) )
        end
        cur = assert( con:execute( string.format( [[SELECT * FROM chatstat WHERE username = '%s']], sNick ) ) )
        row = cur:fetch( {}, "a" )
        cur:close()
        UpdateDateStat( con, row )
        if os.date( "%w" ) ~= 0 then
                if row.switched == 1 then
                        res = assert( con:execute( string.format( [[UPDATE chatstat SET switched = 0 WHERE id='%d' ]], row.id ) ) )
                end
                res = assert( con:execute( string.format( [[SELECT * FROM datestat WHERE field='today']] ) ) )
                tRow = res:fetch( {}, "a" )
                if tRow.value ~= os.date( "%w" ) then
                        ChangeWeekDay = assert( con:execute( string.format( [[UPDATE datestat SET value='%d' WHERE field='today']], os.date( "%w" ) ) ) )
                end
                res:close()
        end
end

datestat 函数仅用于记录聊天及其日期(每天有多少条消息等)。任何帮助都将不胜感激。当前的 UpdateUserStat 函数在值更改方面并未执行任何操作(我昨天进行了检查)。

P.S. 如果需要其他任何东西,并且我可以处理它,我将非常乐意提供它。 :)

原文链接 https://stackoverflow.com/questions/9870991

点赞
stackoverflow用户1027167
stackoverflow用户1027167
将chatstat表的lastweek字段更新为thisweek的值,同时将thisweek字段更新为0,同时将switched字段更新为当前时间,
其中switched字段本来的值所在的周数与当前周数不相等,且当前时间是周日。 
2012-03-26 11:58:48