MySQL 从多个表中复制 SELECT 中的数据

MySQL duplicates data in SELECT from multiple tables

我有6张表,结构如下 我正在使用的查询

SELECT 
    campaigns.idCampaign,

    users.idUser AS idUser,
    users.identification AS userIdentification,
    users.name AS userName,
    campaign_users.commission AS userCommission,
    campaign_files.idFile AS idFile,
    campaign_files.name AS fileName,
    clients.identification AS clientIdentification,
    suppliers.identification AS supplierIdentification
FROM
    campaigns
    LEFT JOIN campaign_users ON( campaigns.idCampaign = campaign_users.idCampaign)
    LEFT JOIN users ON( users.idUser = campaign_users.idUser )
    LEFT JOIN clients USING( idClient )
    LEFT JOIN suppliers ON ( suppliers.idSupplier = campaigns.idSupplier )
    LEFT JOIN campaign_files ON( campaigns.idCampaign = campaign_files.idCampaign)

根据 campaign_files 中的文件数或 campaign_users 中的用户数(较大者),这会导致重复的活动。

这是结果,如您所见 idCampaign 是相同的但多次,我想在单个对象中使用它,像这样

{

    idCampaign: 4,
    users: [
        {
            idUser: 1,
            userName: 'ADMIN' 
        },
        {
            idUser: 2,
            userName: 'Serena Huel'
        }
    ],
    files: [
        {
            idFile: 23,
            fileName: 'dshds9agds86das8gads8g5dsa.hal'
        },
        {
            idFile: 49,
            fileName: 'dshds9agds86das8gads8g5dsa.hal'
        }
        {
            idFile: 84,
            fileName: 'dshds9agds86das8gads8g5dsa.hal'
        },
        {
            idFile: 99,
            fileName: 'dshds9agds86das8gads8g5dsa.hal'
        }
    ],
    clientIdentification: "dolore",
    ...
}

我已经添加了输出作为示例,但它可以是 PHP 对象、数组等

遗憾的是,这不是 MySQL 的工作方式。您可以执行 GROUP BYGROUP_CONCAT 之类的操作,但这会留下字符串而不是数组。那么为什么不把它变成PHP中想要的对象呢?

假设查询可以 return 多个 campaignId,你可以这样做

$campaigns = array();

while ($row = /* fetch row */) {
    if (!isSet($campaigns[ $row['campaignId'] ])) {
        //new campaignId
        $campaigns[ $row['campaignId'] ] = array(
            'users' => array(),
            'files' => array(),
            'clientIdentification' => $row['clientIdentification']
        );
    }

    if (!isSet($campaigns[ $row['campaignId'] ]['users'][ $row['idUser'] ])) {
        //new user
        $campaigns[ $row['campaignId'] ]['users'][ $row['idUser'] ] = $row['userName'];
    }

    $campaigns[ $row['campaignId'] ]['files'][] = array(
        'idFile' => $row['idFile'],
        'fileName' => $row['fileName']
    );
}

这将为您提供一个数组 $campaigns,这几乎就是您想要的。使用 id 作为键保存用户是一种没有任何重复用户的简单方法。现在要获得预期的对象,您可以执行类似

foreach ($campaigns as $c) {
    $expectedObj = array(
        'idCampaign' => $c['idCampaign'],
        'users' => array(),
        'files' => $c['files'],
        'clientIdentification' => $c['clientIdentification']
    );
    foreach ($c['users'] as $idUser => $userName) {
        $expectedObj['users'][] = array(
            'idUser' => $idUser,
            'userName' => $userName
        );
    }
    // use $expectedObj
}