我有这三个查询,我需要合并为一个。
$sql = "SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber";
$sql1 = "select dataplan as currentplan from maindata GROUP BY phonenumber";
$sql2 = "SELECT DISTINCT phonenumber AS value_sum1 FROM maindata";
所以我可以在三列中显示它们:
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["phonenumber"] . "</b></td> ";
echo "</TABLE>";
}
我已经使用了UNION,它只是生成一个大的列,所有数据都是正确的,但是我需要它们全部显示在三列的一个表中。感谢您的任何想法,如果您认为我应该打扮自己,已经完成了:)
答案 0 :(得分:2)
使用GROUP BY
关键字创建不同的记录并对其余值求和。
SELECT phonenumber,
dataplan AS currentplan,
SUM(datamb) AS value_sum
FROM maindata
GROUP BY phonenumber, dataplan;
此查询将为您提供电话号码和数据计划的唯一组合,并将对这些不同组中的datamb
字段求和。这是学习GROUP BY
关键字的一种很好的做法,这对于这种计算非常有用。
编辑:当您看到DISTINCT
时,可以提示您还可以GROUP BY
该字段。这意味着该列或列组中可能存在重复值。确保为此特定字段组定义了一个键,其顺序与ORDER BY
子句相同,以实现最高效率。
答案 1 :(得分:-1)
$ sql1中的非法组
请告知自己使用group by。
http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html
查询将是 非法分组:
select
SUM(datamb) AS value_sum,
dataplan as "first plan row value in this table for this phone number",
phonenumber AS value_sum1
FROM maindata
group by phonenumber
或没有:
select
SUM(datamb) AS value_sum,
dataplan as currentplan ,
phonenumber AS value_sum1
FROM maindata
group by phonenumber, dataplan