我想删除具有相同norad_cat_id
的SQL数据库中的行。由于我的数据库中的数据每天都会更新,因此将添加具有相同norad_cat_id
的新行。我想要做的是删除所有具有相同的norad_cat_id
的行,只留下最近添加的行。到目前为止,我已经尝试从堆栈溢出(其中没有工作)的几个解决方案:Laravel - 删除SQL数据库中的重复行
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('/');
}
编辑:
I我想我需要给出一个清晰的解释,我想实现的目标是:我的数据库会自动更新。我希望能够做的是创建一个行,如果norad_cat_id
不存在于数据库中。如果它已经存在,我希望它采用与norad_cat_id
相同的行,将其删除并仅使用我的数据库中的时间戳保留最近的行。所以我有每个norad_cat_id
之一。
我正在看着这个:https://laravel.com/docs/5.4/eloquent#deleting-models和https://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在你的表? –
在mysql或sql-server之间进行选择,你不能同时使用 – GuidoG
可以尝试在Laravel中运行raw sql吗?例如 DB :: select(DB :: raw(“SELECT * FROM some_table WHERE some_col ='$ someVariable'”)); 看看如何删除mysql上的重复行; https://stackoverflow.com/questions/4685173/delete-all-duplicate-rows-except-for-one-in-mysql –