简体   繁体   English

Mysql:从表中删除ID,除了选择中的行?

[英]Mysql: Delete from table where ID, except rows in a selection?

The problem问题

I'm using buddypress for Wordpress it has a table for private messages in side which are thread ids for message threads.我正在将 buddypress 用于 Wordpress,它在侧面有一个用于私人消息的表,这些表是消息线程的线程 ID。 Currently there's no limit on how many messages can be in a thread.目前,一个线程中可以包含多少条消息没有限制。

I want to create a command that deletes all but the most recent 10 messages in a thread.我想创建一个命令,删除线程中除最近 10 条消息之外的所有消息。 Below is the logic, but I'm not sure the correct syntax to do it?下面是逻辑,但我不确定这样做的正确语法?

Any of you mysql geniuses know the answer?你们中的任何一个 mysql 天才知道答案吗?

DELETE FROM TABLEA WHERE id = X delete everything with thread ID x DELETE FROM TABLEA WHERE id = X删除带有线程 ID x 的所有内容

EXCEPT 
(SELECT * FROM TABLEA WHERE id = X ORDER BY date_sent DESC LIMIT 10) 

Selects most recent 10 I do not wish deleted.选择最近的 10 个我不想删除。

This should working:这应该工作:

DELETE FROM TABLEA WHERE id = X AND id NOT IN (
    SELECT TOP 10 id FROM TABLEA ORDER BY date_sent DESC
)

The sub-select of this query get the last 10 sent items.此查询的子选择获取最后 10 个发送的项目。 The main query have to delete the item with id X except the item is on the result of the sub-select.主查询必须删除带有 id X 的项目,但该项目位于子选择的结果上。

I'm not sure how the table in buddypress works but I guess TABLEA should have its on primary key id.我不确定 buddypress 中的表是如何工作的,但我猜 TABLEA 应该有它的主键 ID。 If TABLEA does have its own primary key id, here's my solution.如果 TABLEA 确实有自己的主键 ID,这是我的解决方案。

DELETE FROM TABLEA WHERE id = x AND TABLEA_id NOT IN 
    (SELECT TABLEA_id FROM TABLEA WHERE id = x ORDER BY date_sent DESC LIMIT 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM