如何在使用多个联盟和所有(*)数据列时不获取行号?

时间:2013-06-24 16:17:47

标签: mysql get numbers row union

<?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的此类查询的行数,并且不会抓取所有列。

1 个答案:

答案 0 :(得分:1)

无法从您的问题中判断出您需要什么结果。行的 count 在SQL术语中与行号不同。您似乎还不明白如何使用COUNT和GROUP BY.这很重要,因为您的问题没有描述您想要的内容,并且尝试帮助您的人必须根据您的查询进行猜测。

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

也许您希望1月和2月表格中的总行数对您的报告有用吗?

尝试此操作来总结您的1月数据。您可以在二月份使用类似的查询,但我会留给您。

   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

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

(评论者是正确的:使用这段代码,你要求一个破解者使用sql注入来破坏你的数据库。使用mysqli转移到预备语句。)