删除所有行并保留最新的x

时间:2010-07-22 19:18:50

标签: mysql sql-delete

我有一张像

这样的表格
entryid,  roomid
 1           1      
 2          55
 3           1
 4          12
 5           1
 6          44
 7           1
 8           3
 9           1

现在我想删除roomid = 1的所有条目并保留 最新的3来自roomid = 1(只有一个命令最好)

所以最后入场:1& 3被删除,入境6,7,9保持住(肯定所有其他的房间仍将留下)

修改: 感谢帮助。下面我为所有感兴趣的人添加了我自己的解决方案

我开始new Question如何将其带入ONE命令。你可以帮助我。

6 个答案:

答案 0 :(得分:2)

DELETE支持ORDER BYLIMIT子句,因此有可能。但是,由于DELETE的参考限制和LIMIT参数,您需要进行两次查询。

SELECT COUNT(*) AS total FROM table  WHERE roomid = 1;
-- run only if count is > 3
DELETE FROM table WHERE roomid = 1 LIMIT total - 3;

请注意,这可能需要中间技术。我已经展示了查询以供参考。

答案 1 :(得分:1)

您可以将多余房间的ID存储在临时表中,并根据以下内容进行删除:

create temporary table tmpTable (id int);

insert  tmpTable
        (id)
select  id
from    YourTable yt
where   roomid = 1
        and 3 <=
        (
        select  count(*)
        from    YourTable yt2
        where   yt2.roomid = yt.roomid
                and yt2.id > yt.id
        );

delete  
from    YourTable
where   ID in (select id from tmpTable);    

这导致:

ID  roomid
2   55
4   12
5   44
6   1
7   1
8   3
9   1

答案 2 :(得分:1)

SET @deleting = (SELECT COUNT(*) FROM tbl WHERE roomid = 1) - 3;
-- run only if @deleting is > 0
PREPARE stmt FROM 'DELETE FROM tbl WHERE roomid = 1 ORDER BY entryid LIMIT ?';
EXECUTE stmt USING @deleting;

答案 3 :(得分:0)

这样的东西
delete from TABLE 
where roomid=1 
   and entryid not in 
   (select entryid from TABLE where roomid=1 order by entryid desc limit 0, 3)

可能有用。

答案 4 :(得分:0)

这里的T-SQL家伙,但可以t-sql做:

SELECT
    *
FROM 
    TABLE A

    LEFT JOIN (SELECT TOP 3 entryID FROM TABLE WHERE roomID = 1 ORDER BY entryID DESC) B
    ON A.entryID = B.entryID 
WHERE       
    A.roomID = 1 AND
    B.entryID IS NULL

然后用DELETE TABLE FROM ...

替换select

答案 5 :(得分:0)

感谢您的所有帮助..我把它们全部放在一起并立即使用此解决方案:) 对我来说,这一步是关闭的。感谢。

// Delete older comments from room 1 (keep last 3 left)
// Step 1:
$sql_com = "SELECT id FROM `mytable` WHERE roomid = '1'";
$result = mysql_query ($sql_com); $num_rows = mysql_num_rows($result);       

// Step 2:
if ($num_rows > 3) {
  $sql_com = "SELECT id FROM `mytable` WHERE roomid = '1' ORDER BY id DESC LIMIT 3,1";  
  $result = mysql_query ($sql_com);
  $row = mysql_fetch_array($result, MYSQL_NUM);
}

// Step 3:  
$sql_com = "DELETE FROM `mytable` WHERE roomid = '1' AND id < ".$row[0];
$result = mysql_query ($sql_com);