MYSQL针对同一数据的多个组的单个查询

时间:2017-03-22 05:16:18

标签: php mysql

我有两个查询来获取唯一IP的rate的计数和总和。

date查询一个群组,然后按country

查询两个群组

这是表格

DROP TABLE IF EXISTS `stats`;
CREATE TABLE IF NOT EXISTS `stats` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` int(5) UNSIGNED NOT NULL,
  `country` int(3) UNSIGNED NOT NULL,
  `user_ip` int(50) UNSIGNED NOT NULL,
  `timestamp` int(10) UNSIGNED NOT NULL,
  `rate` int(7) UNSIGNED NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `stats`
--

INSERT INTO `stats` (`id`, `user_id`, `country`, `user_ip`, `timestamp`, `rate`) VALUES
(1, 1, 1, 1111111111, 1489999983, 15000),
(2, 1, 2, 1111111112, 1489999984, 10000),
(3, 1, 1, 1111111111, 1489999985, 10000),
(4, 1, 1, 1111111111, 1490086333, 10000),
(5, 1, 2, 1111111111, 1490086334, 10000),
(6, 1, 1, 1111111121, 1490086335, 10000);

这些是我用来获取数据的查询

要根据date获取费率总和,请使用以下查询

SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`  
FROM (
    SELECT DISTINCT `user_ip`, `rate`, `timestamp`
    FROM `stats`.`stats`
    WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
    GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY DATE(FROM_UNIXTIME(`timestamp`))

Result
date        count  rate
20-03-2017   2     25000 
21-03-2017   2     20000

要根据country获取费率总和,请使用以下查询

SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`, `country`  
FROM (
    SELECT DISTINCT `user_ip`, `rate`, `timestamp`, `country`
    FROM `stats`.`stats`
    WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
    GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY `country`

Result
country    count    rate
1           3       35000
2           1       10000

由于这两个查询几乎相同,并且从表中获取相同的行,因此可以从单个查询而不是两个查询中获取结果。

另外请建议是否可以在PHP中有效地完成,而不是MYSQL。

由于

1 个答案:

答案 0 :(得分:0)

在php中试试这个

$country="";
$groupByCondition="DATE(FROM_UNIXTIME(`timestamp`))";

if(/*BasedOnCountry*/){
    $country=", `country`";
    $groupByCondition = "`country`";
}

$query= "SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`"+ $country +"  
        FROM (
            SELECT DISTINCT `user_ip`, `rate`, `timestamp`"+ $country +"
            FROM `stats`.`stats`
            WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
            GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
            ) c
        GROUP BY "+ $groupByCondition ;

//execute the query and get the results