mysql 查找不同关系上具有重复值的实体

pdtvr36n  于 2023-08-02  发布在  Mysql
关注(0)|答案(1)|浏览(110)

我有一个动态表单生成器,它有3个表

fields : id , title , type (int,string,image ,.... )

user_forms :  id , user_id , ... 

user_form_fields : id, field_id , user_form_id , value

字符串
假设我有两个字段,分别为product modelserial number

fields : id , title
          1   PRODUCT MODEL
          2   SERIAL NUMBER


当用户注册表单并发送序列号为666的modelX时,我将它们存储在user_form_fields表中,如下所示

user_form_fields : field_id , user_form_id , value 
                      1            1         modelX
                      2            1         666


我注意到由于一些前端错误,我们一直在接收两个字段的相同值…就像我们已经为序列和型号字段存储了666值一样,好消息是我们可以手动纠正这个问题,并根据序列号找到型号。但我需要找到这些形式与错误的字段值第一
现在我必须从数据库中读取所有的表单,并在代码上检查重复值的关系

$userForms = \App\Models\UserForm::with('UserFormFields')
    ->get();
    
    foreach ($userForms as $k=>$userForm)
    {
        $modelNumber  = $userForm->UserFormFields->firstWhere('field_id' , 1 );
        $serialNumber = $userForm->UserFormFields->firstWhere('field_id' , 2 ) ;

        if(  $modelNumber->value == $serialNumber ->value)
        {
           /// corect data
        }

    }


由于我在db中有~ 200万条记录,我一直在循环中用完ram。我想知道是否有一种方法可以在数据库级别进行这种检查,并且只获得具有2关系中重复值的表单,因此我可以创建一个队列来逐个处理它们

bzzcjhmw

bzzcjhmw1#

尝试对user_form_fields表使用自联接来查找型号和序列号值重复的表单。

原始SQL

SELECT uff1.user_form_id
FROM user_form_fields uff1
JOIN user_form_fields uff2 ON uff1.user_form_id = uff2.user_form_id
WHERE uff1.field_id = 1 -- Product Model field_id
AND uff2.field_id = 2 -- Serial Number field_id
AND uff1.value = uff2.value;

字符串

使用Laravel:

$duplicateForms = DB::select("
    SELECT uff1.user_form_id
    FROM user_form_fields uff1
    JOIN user_form_fields uff2 ON uff1.user_form_id = uff2.user_form_id
    WHERE uff1.field_id = 1
    AND uff2.field_id = 2
    AND uff1.value = uff2.value
");

// Loop through the duplicateForms and process them as needed
foreach ($duplicateForms as $form) {
    $userForm = \App\Models\UserForm::with('UserFormFields')->find($form->user_form_id);
    // Process the correction for the form
    // ...
}

相关问题