2017-03-22 44 views
0

我有兩個查詢得到計數和總和爲rate獨特的IP。MYSQL單個查詢多個組通過相同的數據

查詢一個組由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有效地完成。

感謝

回答

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 
+0

這將仍然執行查詢兩次一個日期秒的國家。 –