更新完整表,交换列

时间:2012-03-26 11:07:17

标签: mysql lua ptokax

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

该表有很多行(接近1000行),并且几乎每天都在增加。我想要做的是每周交换两列的值(和月份;如下所述),并将其中一列值设置为零。

我的表的create语句是这样的:

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。 如果需要其他任何东西,我可以管理它,我会非常乐意提供它。 :)

1 个答案:

答案 0 :(得分:1)

update chatstat set lastweek = thisweek, thisweek = 0, switched = NOW() 
where WEEK(switched) <> WEEK(NOW()) and (DAYOFWEEK(NOW()) = 1);