使用 CodeIgniter 从数据库中删除除前 50 行以外的所有行
Delete all but top 50 rows from DB with CodeIgniter
我在尝试提出请求时遇到了很多错误。我想从按计数排序的关键字 table 中获取前 50 个 ID,然后删除其余的。知道这里可能发生了什么吗?
我在发出请求时收到 500 内部服务器错误...
//1. get ids of top 50
$this->CI->db->query("SELECT id FROM keywords ORDER BY count DESC LIMIT 50");
$top_fifty = $this->CI->db->get();
//return $top_fifty;
//2. loop through and create string of ids "1,2,3,4,5"
$top_fifty_string = implode(",", $top_fifty);
// 3. DELETE FROM keywords WHERE id NOT IN(string created in step 2)
$this->CI->db->query("DELETE FROM keywords WHERE id NOT IN($top_fifty_string)");
尝试写成子查询:
$this->CI->db->query("DELETE FROM keywords WHERE id NOT IN(SELECT id FROM keywords ORDER BY count DESC LIMIT 50)");
固定功能:
// //1. get ids of top 50
$top_fifty = $this->CI->db->query("SELECT id FROM keywords ORDER BY count DESC LIMIT 50 ");
// //2. array of ids to string "1,2,3,4,5"
$output ="";
foreach ($top_fifty->result() as $k) {
$output .= $k->id . ",";
}
$top_fifty_string = rtrim($output, ",");
// // 3. DELETE FROM keywords WHERE id NOT IN(string created in step 2)
$this->CI->db->query("DELETE FROM keywords WHERE id NOT IN(.$top_fifty_string.)");
我在尝试提出请求时遇到了很多错误。我想从按计数排序的关键字 table 中获取前 50 个 ID,然后删除其余的。知道这里可能发生了什么吗?
我在发出请求时收到 500 内部服务器错误...
//1. get ids of top 50
$this->CI->db->query("SELECT id FROM keywords ORDER BY count DESC LIMIT 50");
$top_fifty = $this->CI->db->get();
//return $top_fifty;
//2. loop through and create string of ids "1,2,3,4,5"
$top_fifty_string = implode(",", $top_fifty);
// 3. DELETE FROM keywords WHERE id NOT IN(string created in step 2)
$this->CI->db->query("DELETE FROM keywords WHERE id NOT IN($top_fifty_string)");
尝试写成子查询:
$this->CI->db->query("DELETE FROM keywords WHERE id NOT IN(SELECT id FROM keywords ORDER BY count DESC LIMIT 50)");
固定功能:
// //1. get ids of top 50
$top_fifty = $this->CI->db->query("SELECT id FROM keywords ORDER BY count DESC LIMIT 50 ");
// //2. array of ids to string "1,2,3,4,5"
$output ="";
foreach ($top_fifty->result() as $k) {
$output .= $k->id . ",";
}
$top_fifty_string = rtrim($output, ",");
// // 3. DELETE FROM keywords WHERE id NOT IN(string created in step 2)
$this->CI->db->query("DELETE FROM keywords WHERE id NOT IN(.$top_fifty_string.)");