在MySQL中,我有两个几乎相同的结构表,包含不同的数据......我想加入这两个表,并从两个表中得到一列的总和。
$fb_sql = "SELECT campaign_name, adset_name, SUM(reach) AS reach, cpc, id_name, clicks, SUM(amount_spent) AS amount
FROM $table
WHERE id_campaign_shortname = '". $_GET["lpage"] ."' $where
AND date_from = '". $date_from ."'
AND date_to = '". $date_to ."'
GROUP BY id_name";
$google_sql = "SELECT campaign_name, SUM(reach) AS reach, cpc, id_name, clicks, SUM(amount_spent) AS amount
FROM google_msn_adwords_data
WHERE id_campaign_shortname = '". $_GET["lpage"] ."'
AND date_from = '". $date_from ."'
AND date_to = '". $date_to ."'
GROUP BY id_name";
但是我希望将两个表合并为一个输出,但是SUM(reach)
和SUM(amount_spent)
作为总值,f.x。
fb_sql
"到达" SUM
为400 google_sql
"&#34} SUM
为450,我的触及输出为850。
我目前正在输出数据:
$merged_data = array_merge($fb_result, $google_result);
$jsonArray = array();
if(count($merged_data) > 0) {
$total = 0;
foreach($merged_data as $elm) {
array_push($jsonArray, array(
"campaign" => array(
"campaignName" => $elm["campaign_name"],
"campaignAdsetName" => $elm["adset_name"],
"campaignReach" => $elm["reach"],
"campaignSpend" => $elm["amount"],
"campaignCPC" => $elm["cpc"],
"campaignClicks" => $elm["clicks"],
"campaignId" => $elm["id_name"],
)
)
);
$total += $elm["reach"];
}
$jsonCampaignDataArray = array("campaignData" => $jsonArray);
$jsonTotalReach = array("totalReach" => $total);
$finalArray = array_merge($jsonCampaignDataArray, $jsonTotalReach);
$json = json_encode($finalArray);
echo $_GET['jsoncallback']. '('. $json . ')';
但正如所描述的,我想要"合并"在MYSQL级别上作为单个组合结果发生。
答案 0 :(得分:0)
您可以使用加入查询,
eg: SELECT bus.id, SUM( bus.type + rate.rating )
FROM `business` bus
JOIN ratings rate ON rate.bus_id = bus.id where rate.bus_id=1;
答案 1 :(得分:0)
根据MySQL documentation:
UNION用于组合多个SELECT语句的结果 到一个结果集。
看起来像这样:
(SELECT * FROM table1)
UNION
(SELECT * FROM table2);