我正在尝试优化我的查询,并且我有以下代码:
<?php
$counter = mysql_query("SELECT COUNT(*) AS c FROM table");
$row = mysql_fetch_array($counter);
$count = $row["c"];
if($count>500){
mysql_query("DELETE FROM table");
}
?>
我尝试了以下语法作为测试,它有效:
Select case when (Select count(*) as t from `table`) > 500 then 1 else 2 end
但这会引发错误:
Select case when (Select count(*) as t from `table`) > 500 then (DELETE FROM table) else null end
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM table else null end LIMIT 0, 25' at line 1
我知道存在语法错误,但我的主要问题是为什么当我在条件中放置整数时 case 语句有效,但 delete 语句抛出错误。我尝试了一个 select 语句,它运行良好:
Select case when (Select count(*) as t from `table`) < 500 then (select count(*) from table) else null end
最佳答案
如果您真的想用一个delete
来做到这一点:
delete t
from table t cross join
(select count(*) as cnt from table t) c
where c.cnt > 500;
请注意(正如 BWS 所做的那样)truncate table
更有效,尽管您不能使用 where
子句或 join
with truncate table
关于php - 当总行数超过一个数字时,从表中删除所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27723898/