2010-05-18 60 views
1
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)最後的櫃檯報告日,周,月和年。有關更新的Mysql問題

如果我手動添加,SQL工作正常,但對子查詢無法啓動。

謝謝。 :)

+0

有什麼錯誤? – Hao 2010-05-18 14:27:47

回答

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

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 

,並在情況下,有超過REPORT_NAME,同比指數和REPORT_ID它可能是快。

編輯:如果你遇到ERROR 1093 (HY000): You can't specify target table 'table_name' for update in FROM clause有一個workaround爲此。

一般來說,上面有點難看,我想它不會顯示變得漂亮的跡象。處理上述問題的方法之一,尤其是因爲這顯然是多步驟過程的一部分,所以將這四個ID存儲在某個轉換表中,以便它們可以被過程的不同部分重複使用生成報告。

或者跟蹤應用程序端的ID也是有效的(將它們作爲參數傳遞給更新它們的函數等)。