0

以下每个查询都为我提供了我想要的结果,但我想将它们组合成一个查询。

我想输出 3 列:$row->day, $row->otherPageCount, $row->indexCount

有一张表tracking包含所有数据。

1)。

SELECT COUNT(`page`) AS indexCount FROM `tracking`
WHERE `page` = 'index.php'
AND `date`
BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY)
AND NOW()
GROUP BY DATE(`date`)

2)。

SELECT COUNT(`page`) AS otherPageCount FROM `tracking`
WHERE `page` != 'index.php'
AND `date`
BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY)
AND NOW()
GROUP BY DATE(`date`)

3)。

SELECT DATE(`date`) AS day FROM `tracking`
WHERE `date`
BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY)
AND NOW()
GROUP BY DATE(`date`)
4

2 回答 2

4
SELECT DATE(`date`),
       COUNT(`page`) AS indexCount, 
       SUM(`page` = 'index.php') as idx_count, 
       SUM(`page` <> 'index.php') as not_idx_count
FROM `tracking`
WHERE `date` BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY) AND NOW()
GROUP BY DATE(`date`)
于 2013-10-10T11:04:17.897 回答
2

您可以为此使用 IF:

SELECT DATE(`date`), 
  SUM( IF( `page` = 'index.php', 1, 0 ) ) indexCount, 
  SUM( IF( `page` != 'index.php', 1, 0 ) ) otherPageCount
FROM `tracking`
WHERE `date` BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY) AND NOW()
GROUP BY DATE(`date`)

于尔根的回答做同样的事情,但使 IF 隐含。如果您了解它的工作原理,那将是更好的答案。

于 2013-10-10T11:07:06.323 回答