全部更新,除了最后一个

时间:2015-11-22 19:19:45

标签: mysql sql-update

我有一张这样的表:

table_documents
document_id
document_folder_id
document_title
document_notify_expired

ID    FOLDER    TITLE    Notify Expired
1     2         Test1    1
2     2         Test2    1
3     2         Test3    1
4     2         Test4    1
5     2         Test5    1     

我想更新并为所有记录设置document_notify_expired为0,除了最后一个,对于下面的特定文件夹

ID    FOLDER    TITLE    Notify Expired
1     2         Test1    0
2     2         Test2    0
3     2         Test3    0
4     2         Test4    0
5     2         Test5    1     

这是我的代码,但未按预期更新

UPDATE table_documents docs
LEFT OUTER JOIN ( SELECT * FROM table_documents ORDER BY document_id DESC LIMIT 1 )last_doc ON last_doc.document_id = docs.document_id
SET doc.document_notify_expired = '0'
WHERE document_folder_id = '2'
AND last_doc.document_notify_expired = '1'

2 个答案:

答案 0 :(得分:3)

试试这个

UPDATE table_documents docs
    INNER JOIN
(SELECT 
    MAX(id) id
FROM
    table_documents) docsmax ON docs.id != docsmax.id 
SET 
document_notify_expired = 0;

显然最后一行的id最大,所以在连接之后这行不会出现,这将返回所有其他行,你可以随意使用它们。

答案 1 :(得分:-1)

update table1.table_documents
set table1.document_notify_expired = 0
where table1.document_folder_id = 2
    and not table1.document_id = (
        select table2.document_id
        from table_documents as table2
        where table2.document_folder_id = 2
        order by table2.document_id desc
        limit 1
    );