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

时间:2015-05-10 13:15:27

标签: php mysql database many-to-many

根据以下结构,我有6张桌子 erd 我正在使用的查询

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中的用户数量(更高),会导致重复的广告系列。

the result of the query 这是结果,因为你可以看到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对象,数组等。

1 个答案:

答案 0 :(得分:1)

可悲的是,这不是MySQL的工作原理。你可以做一个GROUP BY和类似GROUP_CONCAT的东西,但是这会留下字符串而不是数组。那么为什么不把它变成PHP中的想要的对象呢?

假设查询可以返回多个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
}