2

我有一张像

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

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

所以最后 entryid: 1 & 3 被删除并且 entryid 6, 7, 9 继续保留(确保所有其他 roomid 仍然保留)

编辑:感谢您的帮助。下面我添加了我自己的解决方案,供大家感兴趣

我开始了一个新问题,如何将它带入一个命令。你可以在那里帮助我。

4

6 回答 6

2

DELETE支持ORDER BYandLIMIT子句,所以它是可能的。但是,由于DELETE's 的引用限制和参数,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;

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

于 2010-07-22T19:32:18.167 回答
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
于 2010-07-22T19:27:22.620 回答
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;
于 2010-07-22T19:44:37.690 回答
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)

可能会奏效。

于 2010-07-22T19:25:11.927 回答
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

然后将 select 替换为 DELETE TABLE FROM...

?

于 2010-07-22T19:37:30.180 回答
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);
于 2010-07-23T08:56:11.653 回答