检查数据库中大量值的唯一性


Check large chunk of values for uniqueness in database

我需要创建长度应较短(约6个字符)的促销代码。促销代码必须是唯一的,所以我需要在数据库中检查它们的唯一性。它们需要以数千的批量生成,因此每次生成优惠券都要检查数据库是不可行的。我创建了一个方法,首先生成所需数量的优惠券,然后使用where in()检查重复项。重复计数大于零,使其再次生成计数。

public function generateCoupons($count, $length = 6)
{
    $coupons = [];
    while(count($coupons) < $count) {
        do {
            $coupon = strtoupper(str_random($length));
        } while (in_array($coupon, $coupons));
        $coupons[] = $coupon;
    }
    $existing = Offer::whereIn('coupon', $coupons)->count();
    if ($existing > 0)
        $coupons += $this->generateCoupons($existing, $length);
    return (count($coupons) == 1) ? $coupons[0] : $coupons;
}

需要如何改进的建议吗?或者,如果我可以用其他方式来实现同样的目标。

确保促销代码已在数据库中建立索引。这将加快搜索现有的促销代码。

否则,你的方法是好的!您希望一次检查尽可能多的代码(使用whereIn/count进行检查),并且只重新生成不唯一的代码。

构建一个包含1000个候选者的表new_codes。CCD_ 2。

DELETE new_codes
    FROM new_codes
    LEFT JOIN existing_codes ON existing_codes.code = new_codes.code
    WHERE existing_codes.code IS NOT NULL;

这(如果我做得对的话)会很快删除重复。现在您将拥有not-quite-1000个"好"代码。