关于UPDATE的Mysql问题

时间:2010-05-18 13:57:00

标签: mysql

UPDATE counter_reports 
SET `counter`=`counter`+1,`date`=?
WHERE report_id IN(
                   (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `year`=1 
                    ORDER BY report_id DESC LIMIT 1),
                   (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `month`=1 
                    ORDER BY report_id DESC LIMIT 1),
                   (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `week`=1 
                    ORDER BY report_id DESC LIMIT 1),
                   (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `day`=1 
                    ORDER BY report_id DESC LIMIT 1)
                  )

这样的sql还有其他选择吗?我需要更新(递增1)上一天,每周,每月和每年的计数器报告。

如果我手动添加,sql工作正常,但是子查询无法启动。

感谢。 :)

2 个答案:

答案 0 :(得分:1)

MySQL有点蹩脚,这样做,会起作用:

UPDATE counter_reports 
SET `counter`=`counter`+1,`date`=?
WHERE report_id IN(
                   (select report_id from (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `year`=1 
                    ORDER BY report_id DESC LIMIT 1) as x),
                   (select report_id from (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `month`=1 
                    ORDER BY report_id DESC LIMIT 1) as x),
                   (select report_id from (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `week`=1 
                    ORDER BY report_id DESC LIMIT 1) as x),
                   (select report_id from (SELECT report_id 
                    FROM counter_reports 
                    WHERE report_name="emails_sent" AND `day`=1 
                    ORDER BY report_id DESC LIMIT 1) as x)
                  )

另请参阅此处的最后一个示例(与您的问题相关的Mysql代码):http://mssql-to-postgresql.blogspot.com/2007/12/deleting-duplicates-in-postgresql-ms.html

答案 1 :(得分:0)

什么不起作用,错误是什么?

上述子查询可能有点改进

SELECT report_id 
FROM counter_reports 
WHERE report_name="emails_sent" AND `year`=1 
ORDER BY report_id DESC LIMIT 1

相当于

SELECT max(report_id)
FROM counter_reports
WHERE report_name="emails_sent" AND `year`=1

如果有一个index_name,year和report_id的索引可能很快。

编辑:如果您遇到ERROR 1093 (HY000): You can't specify target table 'table_name' for update in FROM clause,则会有workaround

一般来说,上面的内容有点难看,我想它不会显示出变得更漂亮的迹象。处理上述问题的方法之一,特别是因为这显然是多步骤程序的一部分,就是将这四个id存储在某个转换表中,在这些转换表中,它们可以被进程的不同部分重用。制作报告。

另外,跟踪应用程序端的id也会很有效(将它们作为参数传递给更新它们的函数等等。)。