如何在magento 2中使用Group By和Having Clause SQL查询?

Magento Group By SQL 查询用于从指定列中获取相同的值集。虽然我们使用带有聚合函数的 group by 子句

我们必须使用Having子句,并且不能将where子句与Group By Aggregrate 函数一起使用。

聚合函数,如 MIN、MAX、COUNT、AVG、SUM 等……

让我们举个例子,从customer_entity表中查找重复的电子邮件。

如果您将多个网站用作网站,则可能会出现重复的电子邮件。每个网站都有自己的电子邮件 ID,并且一个网站电子邮件不适用于其他网站。

在这里,我们将使用 group by 和 SQL 子句找到重复的电子邮件计数,

<?php declare(strict_types=1);

namespace Rbj\Customer\Model;

use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;

class General
{
    /**
     * @var CollectionFactory
     */
    private $customerRepository;

    public function __construct(
        CollectionFactory $customerCollectionFactory
    ) {
        $this->customerCollectionFactory = $customerCollectionFactory;
    }

    public function findDuplicateEmail()
    {
        $customerCollection = $this->customerCollectionFactory->create();

        $customerCollection->getSelect()
            ->columns(['emailCount' => 'COUNT(e.entity_id)'])
            ->group('email')
            ->having('emailCount > ?', 1);
        return $customerCollection;
    }
}

这里我们在构造函数中添加了一个客户集合工厂来获取客户集合。

我们使用group() 子句和提供的电子邮件从 customer_entity 表中查找电子邮件字段。

我们使用having() 子句是因为我们在查询中使用了计数聚合。我们正在检查 emailCount 条件的 emailCount 是否可用超过 1。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论