以SUM和COUNT显示2个表中的数据

时间:2019-04-16 06:55:24

标签: php mysql

我正在尝试使用内部联接,求和和计数显示2个不同表的结果。我在使其工作上遇到了很多困难。


  self.callAPIWithMultiPart("here apiURL", image: dictimage, param: dictparam, type: .post, controller: controller, header: requestHeader, successBlock: successBlock, failureBlock: failureBlock)

我需要通过以下方式显示

Table properties
+----+--------+---------+-------+-------+
| id | idname | address | pic1  | ll_id |
+----+--------+---------+-------+-------+
|  1 | apt1   |    1344 | 1.jpg |     1 |
|  2 | apt2   |    1345 | 2.jpg |     1 |
+----+--------+---------+-------+-------+

Table transactions
+----+-------------+---------+
| id | property_id | revenue |
+----+-------------+---------+
|  1 |           1 |    1000 |
|  2 |           1 |     500 |
|  3 |           2 |     300 |
|  4 |           2 |     100 |
+----+-------------+---------+

这是我正在使用的代码

+------+---------+-------+--------------+-------------+
| name | address |  pic  | total(count) | total (sum) |
+------+---------+-------+--------------+-------------+
| apt1 |    1344 | 1.jpg |            2 |        1500 |
| apt2 |    1345 | 2.jpg |            2 |         400 |
+------+---------+-------+--------------+-------------+

谢谢

1 个答案:

答案 0 :(得分:0)

您可以在JOIN查询中执行聚合,而无需使用子查询。请注意,如果属性没有交易,您可能要使用LEFT JOIN

SELECT p.name, p.address, p.pic1 AS pic,
       COALESCE(COUNT(t.property_id), 0) AS `total (count)`,
       COALESCE(SUM(t.revenue), 0) AS `total (sum)`
FROM properties p
LEFT JOIN transactions t ON t.property_id = p.id
WHERE p.ll_id = 1
GROUP BY p.name, p.address, p.pic1

输出:

name    address pic     total (count)   total (sum)
apt1    1344    1.jpg   2               1500
apt2    1345    2.jpg   2               400

Demo on dbfiddle

在PHP中,您可以编写:

$llid = htmlspecialchars($_SESSION["id"]);
$sql = "SELECT p.id, p.name, p.address, p.pic1 AS pic,
       COALESCE(COUNT(t.property_id), 0) AS `transactions`,
       COALESCE(SUM(t.revenue), 0) AS `revenue`
FROM properties p
LEFT JOIN transactions t ON t.property_id = p.id
WHERE p.ll_id = $llid
GROUP BY p.id, p.name, p.address, p.pic1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    // output data of each row
    while($row = $result->fetch_assoc()) {
    ?>
        <tr>
         <td><?php echo $row["name"];?></td>
         <td><?php echo $row["address"];?></td>
         <td> <img src="p3/img/<?php echo $row["pic"];?>" width="80"> </td>
         <td><?php echo $row["transactions"];?></td>
         <td>$<?php echo $row["revenue"];?></td>
         <td> <span>VIEW</span> </td>
        </tr>
<?php

    }

} else {
    echo "No Updates";
}
$conn->close();