gpt4 book ai didi

php - Laravel - 删除 SQL 数据库中的重复行

转载 作者:行者123 更新时间:2023-11-29 10:41:33 25 4
gpt4 key购买 nike

我正在尝试删除 SQL 数据库中具有相同 norad_cat_id 的行。由于我的数据库中的数据每天都会更新,因此将添加具有相同 norad_cat_id 的新行。我想要做的是删除所有具有相同 norad_cat_id 的行,只保留最近添加的行。到目前为止,我已经尝试了 Stack Overflow 上的一些解决方案(没有一个有效):

1:

DB::table('satellites')->select('norad_cat_id')->distinct()->delete();

2:

$deleteDuplicates = DB::table('satellites as n1')
->join('satellites as n2', 'n1.norad_cat_id', '>', 'norad_cat_id')
->where('n1.norad_cat_id', '=', 'n2.norad_cat_id')
->delete();

我的数据库名称是satellite

TL;DR:删除数据库中具有相同 norad_cat_id 的行

编辑:

这是我的完整功能:

    public function displayer(){
$api = new Client([
'base_uri' => 'https://www.space-track.org',
'cookies' => true,
]); $api->post('ajaxauth/login', [
'form_params' => [
'identity' => '#',
'password' => '#',
],
]);
$response = $api->get('basicspacedata/query/class/satcat/orderby/INTLDES%20desc/limit/2/metadata/false');
$data = json_decode($response->getBody()->getContents(), true);
foreach ($data as $attributes) {
$attributes = array_change_key_case($attributes, CASE_LOWER);
Satellite::create($attributes);
}
$deleteDuplicates = DB::table('satellites as n1')
->join('satellites as n2', 'n1.created_at', '<', 'n2.created_at')
->where('n1.created_at', '=', 'n2.created_at') ->delete();
$api->get('ajaxauth/logout');
return redirect('/');
}

编辑:

我想我需要对我想要实现的目标给出一个清晰的解释:我的数据库将自动更新。我想要做的是,如果数据库中尚不存在 norad_cat_id ,则创建一行。如果它已经存在,我希望它获取具有相同 norad_cat_id 的行,将其删除,并仅使用数据库中的时间戳保留最新行。这样我就有了每个 norad_cat_id 之一。

我正在看这个:https://laravel.com/docs/5.4/eloquent#deleting-modelshttps://laravel.com/docs/5.4/database#running-queries 。也许我可以用这个?

编辑2:谁能解释一下我写的这段代码:

DB::select( DB::raw('DELETE n1 FROM satellites n1, satellites n2 WHERE n1.id < n2.id AND n1.norad_cat_id = n2.norad_cat_id'));

我查看了一些答案和其他问题,并尝试提出一些建议。

最佳答案

试试这个,它只会保留重复和非重复的 id 最新 id 和

$deleteDuplicates = DB::table('satellites as n1') 
->join('satellites as n2', 'n1.norad_cat_id', '<', 'n2.norad_cat_id')
->where('n1.norad_cat_id', '=', 'n2.norad_cat_id') ->delete();

回应OP评论:

got an error - SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'norad_cat_id' in on clause is ambiguous

这意味着您必须指定该列引用哪个表...

引用:Delete all Duplicate Rows except for One in MySQL?

编辑

$ids_to_delete = array(1, 2, 3);
DB::table('satellites')->whereIn('norad_cat_id', $ids_to_delete)->delete();

关于php - Laravel - 删除 SQL 数据库中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45372864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com