1
<?php

$result = mysql_query("SELECT COUNT(`uid`), `mac`, SUM(`time`)/60 AS ConnTime, SUM(`download`)/1000000 AS TotalDown, SUM(`upload`)/1000000 AS TotalUp
FROM `cdr_data_january`
WHERE (`towerid` LIKE '".$btsid."') AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
GROUP BY `uid`
UNION
SELECT COUNT(`uid`), `mac_add`, SUM(`time`)/60 AS ConnTime, SUM(`download`)/1000000 AS TotalDown, SUM(`upload`)/1000000 AS TotalUp
FROM `cdr_data_february`
WHERE (`bts` LIKE '".$btsid."') AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
GROUP BY `uid`");

mysql_fetch_row($result); 
$numrows = mysql_num_rows($result);

?>

编辑这里是为了可读性而格式化的 sql。

    SELECT COUNT(`uid`), 
           `mac`, 
           SUM(`time`)/60 AS ConnTime, 
           SUM(`download`)/1000000 AS TotalDown, SUM(`upload`)/1000000 AS TotalUp
      FROM `cdr_data_january`
     WHERE (`towerid` LIKE '".$btsid."') 
       AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
  GROUP BY `uid`
     UNION
    SELECT COUNT(`uid`), 
           `mac_add`, 
           SUM(`time`)/60 AS ConnTime, 
           SUM(`download`)/1000000 AS TotalDown, 
           SUM(`upload`)/1000000 AS TotalUp
     FROM `cdr_data_february`
    WHERE (`bts` LIKE '".$btsid."') 
      AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
 GROUP BY `uid`

上面的行没有返回我的行数。

上面的代码在我用 (*) 抓取整个表格并像 COUNT(*) 一样计数时有效。

请给我一个解决方案,以便我可以获得使用多个 UNION 并且不抓取所有列的此类查询的行数。

4

1 回答 1

1

从您的问题中无法判断您需要什么结果。在SQL 用语中,行数与行数不同。您似乎也不了解如何使用 COUNT 并且GROUP BY. 这很重要,因为您的问题没有描述您想要什么,并且试图帮助您的人必须根据您的查询进行猜测。

您的 UNION 将为 1 月和 2 月的 mac 和 uid 的每个匹配组合返回一行。

或许您想要 1 月和 2 月表格中对您的报告有贡献的总行数?

试试这个来总结你一月份的数据。您可以对二月使用类似的查询,但我将把它留给您。

   SELECT COUNT(*) AS recordcount,
           `uid`,
           `mac`, 
           SUM(`time`)/60 AS ConnTime, 
           SUM(`download`)/1000000 AS TotalDown, 
           SUM(`upload`)/1000000 AS TotalUp
      FROM `cdr_data_january`
     WHERE (`towerid` LIKE '".$btsid."') 
       AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
  GROUP BY `uid`, `mac`

对于 uid 和 mac 的每个不同组合,这将在结果集中为您提供一行。如果您还需要汇总计数,请改用此 GROUP BY。

  GROUP BY `uid`, `mac` WITH ROLLUP

您可能会发现重构您的多月查询很有帮助,如下所示:

   SELECT COUNT(*) AS recordcount,
           `uid`,
           `mac`, 
           SUM(`time`)/60 AS ConnTime, 
           SUM(`download`)/1000000 AS TotalDown, 
           SUM(`upload`)/1000000 AS TotalUp
      FROM (
                SELECT * FROM `cdr_data_january`
                 WHERE (`towerid` LIKE '".$btsid."') 
                  AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
             UNION ALL 
                SELECT * FROM `cdr_data_february`
                 WHERE (`towerid` LIKE '".$btsid."') 
                   AND (`ldate` BETWEEN '".$date1."' AND '".$date2."')
           ) data
  GROUP BY `uid`, `mac` WITH ROLLUP

这将为您的 1 月和 2 月呼叫详细记录的联合中的每个 uid/mac 组合提供一行。请注意,WHERE 子句是重复的,因此您的查询可以利用 crd 表中的索引(如果存在)。

(评论者是正确的:使用此代码,您正在乞求破解者使用 sql 注入侵入并破坏您的数据库。使用 mysqli 转移到准备好的语句。)

于 2013-06-24T16:57:13.977 回答