使用array_search()或SELECT子查询进行INSERT查询会更快吗?

时间:2018-08-07 18:06:39

标签: php mysql performance query-performance

我有两个带有类别的数组,如下例:

$apply_func['categories'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
$apply_func['subcategories'] = ['H','I','J','K','L','M','N'];

我对它们应用了自定义功能,如下所示:

foreach ($apply_func as $name => $values) {
    $$name = custom_func($values);
}

现在我有三个与之相关的表,如下所示:

categories[id, category_name]--------
                                     |------ cat_sub[id, category_id, subcategory_id]
subcategories[id, subcategory_name]--

我很困惑的是,我应该在INSERT中对该特定的 Array

使用哪种方法
$cat_sub = [
    ['category' => 'A', 'subcategory' => 'H'],
    ['category' => 'B', 'subcategory' => 'I'],
    ['category' => 'C', 'subcategory' => 'J'],
    ['category' => 'D', 'subcategory' => 'K'],
    ['category' => 'E', 'subcategory' => 'L'],
    ['category' => 'F', 'subcategory' => 'M'],
    ['category' => 'G', 'subcategory' => 'N']
];

像这样在cat_sub.table上获得此结果:

[category_id , subcategory_id]
[1           , 1             ]
[2           , 2             ]
[3           , 3             ]
[4           , 4             ]
[5           , 5             ]
[6           , 6             ]
[7           , 7             ]

我想到了两种方法:

  1. array_search()

    //Cat_Sub
    $query = "INSERT INTO cat_sub (category_id, subcategory_id) VALUES ";
    foreach ($cat_sub as $catsub) {
      $category = array_search($catsub['category'], $categories)+1;
      $subcategory = array_search($catsub['subcategory'], $subcategories)+1;
      $cats[] = "($category, $subcategory)";
    }
    $query .= implode(',', $cats);
    $pdo->prepare($query)->execute();
    
    //Categories, Subcategories
    foreach ($apply_func as $name => $values) {
        $query = "INSERT INTO $name (".str_replace('ies', 'y', $name)."_name)  VALUES ";
        foreach ($values as $key => $value) {
            $$name[$key] = "($value)";
        }
        $query .= implode(',', $$name);
    }
    $pdo->prepare($query)->execute();
    

  1. SELECT子查询

    //Categories, Subcategories
    foreach ($apply_func as $name => $values) {
    
        $query = "INSERT INTO $name (".str_replace('ies', 'y', $name)."_name) VALUES ";
        foreach ($values as $key => $value) {
            $$name[$key] = "($value)";
        }
        $query .= implode(',', $$name);
    }
    $pdo->prepare($query)->execute();    
    
    
    //Cat_Sub
    $query = "INSERT INTO cat_sub (category_id, subcategory_id) VALUES ";
    foreach ($cat_sub as $catsub) {
      $cats[] = "(
                     (SELECT id FROM categories WHERE category_name = '".$catsub['category']."'),
                     (SELECT id FROM subcategories WHERE subcategory_name = '".$catsub['subcategory']."')
                 )";
    }
    $query .= implode(',', $cats);
    $pdo->prepare($query)->execute();
    

这两种方法都能完成任务,但是我不知道在这种情况下哪种方法更好。

P.S。这些表的索引编制正确,所有id都处于AI模式,实际的 Arrays 具有 +100,000条记录

0 个答案:

没有答案