如何将这3个查询合并为一个MySQL查询?

时间:2013-10-10 11:02:25

标签: php mysql

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

我想输出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`)

2 个答案:

答案 0 :(得分: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`)

答案 1 :(得分: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`)

juergen's answer做同样的事情,但隐含IF。如果你了解它是如何工作的,那就是更好的答案。