从SQL正确的SQL查询显示IP Accounting

时间:2017-09-10 14:42:15

标签: php mysql

我需要帮助以正确的方式查询来显示数据库表中的信息。

我的数据库表包含id |列src_address | dst_address |字节

信息存储在我的MikroTik路由器(IP Accounting)中,但我的脚本将IP地址存储为整数,因此我可以选择范围。

我需要运行正确的查询来显示数据,如下所示:

  • 从src_address到dst_address显示的所有字节都是上传字节
  • 从dst_address到src_address显示的所有字节都是下载字节

(src_address - > dst_address = upload)

(dst_address - > src_address = download)

我需要脚本输出以下内容: IP地址|上传字节|下载字节|总字节数

我当前的脚本只输出上传字节,我不知道如何反转顺序第二次显示下载字节,然后添加两个以显示总字节数。

这是我的代码:

<?php
//Include needed files
require ("config.php");
include ("includes/formatbytes.php");

//Connect to database
$conn = mysqli_connect($SQLserver, $SQLusername, $SQLpassword, 
$SQLdatabase);
if (!$conn) {
    die("Could not connect: " . mysqli_connect_error());
}

//Query database
$query = "SELECT * , SUM(bytes) AS upload_bytes FROM ipaccounting WHERE 
src_address BETWEEN 3232235520 AND 3232301055 AND dst_address NOT BETWEEN 
3232235520 AND 3232301055 GROUP BY src_address";


//Execute query
$result = mysqli_query($conn,$query);


//Display IP information
echo "<table>";
echo "<tr><th>IP Address</th><th>Upload</th></tr>";

while($row = mysqli_fetch_array($result)) {
    if (isset($row['src_address'])) {
        $src_address = $row['src_address'];
        $src_address = long2ip($src_address);
    }
    /*if (isset($row['dst_address'])) {
        $dst_address = $row['dst_address'];
    } */
    if (isset($row['upload_bytes'])) {
        $uploadbytes = $row['upload_bytes'];
        $uploadbytes = formatBytes($uploadbytes);
    } 

    echo "<tr><td>".$src_address."</td><td>".$uploadbytes."</td></tr>";
} 

echo "</table>";
mysqli_close($conn);
?>

注意,在整数3232235520中是192.168.0.1而3232301055是192.168.255.254

1 个答案:

答案 0 :(得分:1)

您需要聚合两次,一次用于上传,一次用于下载:

SELECT address, SUM(upload_bytes) as upload_bytes, 
       SUM(download_bytes) as download_bytes
FROM ((SELECT src_address as address, SUM(bytes) AS upload_bytes, 0 as download_bytes
       FROM ipaccounting
       WHERE src_address BETWEEN 3232235520 AND 3232301055 AND
             dst_address NOT BETWEEN 3232235520 AND 3232301055
       GROUP BY src_address
      ) UNION ALL
      (SELECT dst_address, 0 AS upload_bytes, SUM(bytes) as download_bytes
       FROM ipaccounting
       WHERE dst_address BETWEEN 3232235520 AND 3232301055 AND
             src_address NOT BETWEEN 3232235520 AND 3232301055
       GROUP BY dst_address
      )
     ) a
GROUP BY address;

您还可以以更合理的格式显示IP地址。 MySQL具有IP地址功能(参见here):

select . . . , inet_ntoa(src_address) as src_ip

您也可以在应用层执行此操作。