*首先,感谢first part该问题的帮助:
再次出现情况:
“我在我的表中有”mytable“字段,entryid(自动增量)和roomid ..我想删除所有roomid = 1,除了最后3个”
entryid, roomid
1 1
2 55
3 1
4 12
5 1
6 44
7 1
8 3
9 1
现在我解决了它:
// 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);
现在这个工作正常。
问题:我需要进行第1步,因为如果我的表中的roomid = 1少于3个条目,则在LIMIT 3,1的第2步中我将得到mysql错误。 (限制3,1期望至少有3个条目)。我怎么能解决这个问题,以便我可以删除第1步。
主要问题:如何将所有这三个步骤纳入一步:)这可能吗?如何?
THX 克里斯
P.S。 仅供参考:此例程可以每秒500次启动,数据库包含3Million条目。所以它需要尽可能的资源友好。
答案 0 :(得分:2)
DELETE FROM `mytable` WHERE roomid = '1' AND roomid <= (SELECT * FROM (SELECT roomid FROM `mytable` WHERE roomid = '1' ORDER BY roomid DESC LIMIT 3,1) tmp);
请注意,如果删除“select * from(...)tmp”,则可能会收到错误。
ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
此外,我认为您的代码会删除除最后4行(不是3)之外的所有行。
答案 1 :(得分:1)
DELETE mytable FROM mytable
JOIN (
SELECT id FROM mytable
WHERE roomid = 1
ORDER BY id DESC
LIMIT 3,18446744073709551615
) AS t2
ON mytable.id = t2.id;