此查询的错误在哪里?

时间:2013-10-08 14:38:10

标签: php mysql

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

$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>"; 

}

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

2 个答案:

答案 0 :(得分: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);"

答案 1 :(得分:0)

UNION为查询添加了额外的行。看起来你只想要多列。看看这个查询是否让你更近了;如果没有,请显示一些样本数据和预期结果:

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

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