可以使用join
在delete
語句刪除所有,但最近的一排,當有一個用戶超過五排:
delete t from table t join
(select user_id, max(last_activity) as mla
from table
group by user_id
having count(*) > 5
) mla
on t.user_id = mla.user_id and
t.last_activity < mla.mla;
這會爲所有用戶。對於一個用戶,添加一個where
聲明:
delete t from table t join
(select user_id, max(last_activity) as mla
from table
where user_id = '?'
group by user_id
having count(*) > 5
) mla
on t.user_id = mla.user_id and
t.last_activity < mla.mla;
編輯:
要刪除一行,只需使用min()
,而不是max()
:
delete t from table t join
(select user_id, min(last_activity) as mla
from table
where user_id = '?'
group by user_id
having count(*) > 5
) mla
on t.user_id = mla.user_id and
t.last_activity = mla.mla;
什麼是與使用子查詢的問題? – abl
@ 0101。 。 。我很困惑。你的查詢*刪除*一行('限制1'),但文字說你「必須保留一行」。這是什麼?保留一個還是刪除一個? –
對不起,我以爲我必須刪除一行。謝謝你警告我。 – 0101