我的数据库中有一个表,其中包含多个带有数字的列,我想查询 1 个查询中的所有行,并对数据库中每列中的所有行进行单独的总计。
这样
$sql = '
SELECT sum(TOTAL1)
, sum(TOTAL2)
, sum(TOTAL3)
, sum(TOTAL4)
FROM TABLE WHERE ID = '.$ID.'';
当我使用这样的单列查询执行此操作时,它可以工作。
$sql = 'SELECT sum(TOTAL1) FROM TABLE WHERE ID = '.$ID.'';
但我似乎无法让它在 1 个查询中用于倍数,有没有人知道更合适的方法来执行此操作而不是在单独的查询中?
$sql = 'SELECT (sum(TOTAL1)+sum(TOTAL2)+sum(TOTAL3)+sum(TOTAL4)) AS FINALTOTAL FROM TABLE WHERE ID = '.$ID.'';
使用别名。
旁注:将您的WHERE
子句添加到我在下面给出的测试示例中。
SELECT sum(TOTAL1) as total1, sum(TOTAL2) as total2
如果要使用单独的别名,如果您希望将它们作为不同的实体进行回显,则非常方便。
例如:
$query = mysqli_query($con, "SELECT SUM(col1) as total1,
SUM(col2) as total2,
SUM(col3) as total3 FROM table ");
while($row = mysqli_fetch_array($query)){
echo $row['total1']; // echo'd 125
echo "<br>";
echo $row['total2']; // echo'd 225
echo "<br>";
echo $row['total3']; // echo'd 2000
}
旁注:我的三列包含以下内容:
- Col1 2 排 25, 100
- 2 排 Col2 25, 200
- 2 行 Col3 1000、1000
回显所有行的总和,例如:(和while
循环内部)
$total = $row['total1'] + $row['total2'] + $row['total3'];
echo $total;
或者一口气,作为一个别名和一行回显:
SELECT sum(TOTAL1 + TOTAL2 + TOTAL3) as total FROM table
即:
$query = mysqli_query($con, "SELECT SUM(col1 + col2 + col3) as total FROM table ");
while($row = mysqli_fetch_array($query)){
echo $row['total'];
}
注意:对于要求和的所有字段,数据类型必须相同通过以下查询,您可以拥有 SUM(字段 1)+SUM(字段 2)+ SUM(字段 3) .....n 在 1 个单字段中我只对 2 个字段使用了这个查询,两者都是整数
看到这是我的表定义
create table `siso_area_operativa` (
`id_area_operativa` int ,
`area_operativa` varchar (8),
`responsable` int
);
这是您想要的查询
SELECT SUM(a.field1) FROM
(
SELECT
SUM(id_area_operativa) field1
FROM
siso_area_operativa
UNION ALL
SELECT SUM(responsable) field1
FROM
siso_area_operativa ) AS a
其结果是单个字段中的总和(id_area_operativa) + 总和(负责)
享受!!!!!!!!!!!!