0

我今天从许多不同的方式对此进行了攻击,我还没有想出显示数据的最佳方式是使用可以显示在一个表中的单个查询。问题是我要组合三个查询,但进展并不顺利。我觉得它很接近但显然不正确。

$sql =  (SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from   maindata 

GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);


$result = mysql_query($sql);



if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}



while ($row = mysql_fetch_assoc($result)){

echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
echo "<td><b>Data Plan: ". $row["currentplan"] . "</b></td> "; 
echo "<td><b>Phone Number: ". $row["value_sum1"] . "</b></td> ";  
echo "</TABLE>"; 

}

问题是我想要三列数据,而我只得到一列包含所有数据

4

2 回答 2

0

首先替换这一行:

$sql =  (SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from   maindata GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);

经过

$sql =  "(SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber UNION select dataplan as currentplan from   maindata GROUP BY phonenumber UNION SELECT DISTINCT phonenumber AS value_sum1 FROM maindata);"
于 2013-10-08T14:48:32.773 回答
0

UNION向查询中添加额外的行。看起来你只想要多列。看看这个查询是否能让你更接近;如果不是,请显示一些示例数据和预期结果:

SELECT
  phonenumber AS value_sum1
  dataplan AS currentplan,
  SUM(datamb) AS value_sum
FROM maindata
GROUP BY
  phonenumber,
  dataplan

另外,请考虑不要phonenumberdataplan列起别名——在这种情况下,别名只会混淆事物。您需要相应地更改 PHP 代码中的索引值。

于 2013-10-08T14:50:05.800 回答