![](/img/trans.png)
[英]How to count the total number of values from various rows, when each row has multiple data seperated by comma?
[英]Delete all rows from a table when total row count exceeds a number
我正在嘗試優化查詢,並且有以下代碼:
<?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-您的SQL語法有誤; 檢查與您的MySQL服務器版本相對應的手冊以獲取正確的語法,以在第1行的'DELETE FROM table else null end LIMIT 0,25'附近使用
我知道語法上有錯誤,但是我的主要問題是,當我將整數放在條件中時,為什么case語句起作用,但是delete語句會引發錯誤。 我嘗試了一條選擇語句,它運行良好:
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
以截斷表
如果您要刪除表中的所有行,只需使用“ TRUNCATE table”
當SELECT
語句產生單個值時, CASE
語句與SELECT
一起使用(即,它僅選擇一列,並且結果集只有一行); 否則它不起作用。 顯然, DELETE
(或INSERT
, UPDATE
等)永遠不會在該位置工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.