我必须从mysql表中计算几个日期范围(今天,周,月)中的行。
目前我在PHP脚本中运行循环并对每个日期范围进行单独查询,我知道这是一个坏主意。
<?php
$now = "2016-04-21";
$today = $now;
$week = date( 'Y-m-d', strtotime( '-7 day', strtotime( $now ) ) );
$month = substr( $now, 0, 7 );
$res1 = mysql_query("SELECT SUM(pageview) FROM statistics WHERE user = '$id' AND DATE_FORMAT( date, '%Y-%m-%d' ) = '$today'" );
$res2 = mysql_query("SELECT SUM(pageview) FROM statistics WHERE user = '$id' AND ( t.date BETWEEN ( '$week' ) AND ( '$today' ) )");
$res3 = mysql_query("SELECT SUM(pageview) FROM statistics WHERE user = '$id' AND DATE_FORMAT( t.date, '%Y-%m' ) = '$month'" );
所以我想使用SINGLE QUERY这样做。
我找到了count rows in multiple date ranges和query for grabbing multiple date ranges,但我不确定哪个是最好的,以及如何处理我的情况
答案 0 :(得分:1)
如果您确实想使用一个查询检索这三个值:
$res = mysql_query("
SELECT sum1, sum2, sum3
FROM (SELECT SUM(pageview) AS sum1 FROM statistics WHERE user = '$id' AND DATE_FORMAT( date, '%Y-%m-%d' ) = '$today') AS T1
JOIN (SELECT SUM(pageview) AS sum2 FROM statistics WHERE user = '$id' AND ( t.date BETWEEN ( '$week' ) AND ( '$today' ) )) AS T2
JOIN (SELECT SUM(pageview) AS sum3 FROM statistics WHERE user = '$id' AND DATE_FORMAT( t.date, '%Y-%m' ) = '$month') AS T3");
虽然这不是更好的表现,但我真的没有理由这样做。
P.S。将变量插入这样的查询是一个坏习惯。在这种情况下你的安全,但如果你使用用户输入的变量,你可以打开SQL注入。尝试学习prepared statements
答案 1 :(得分:1)
您可以按OR
组合所有条件,以选择一个查询中的所有数据。并且可以在SELECT
中使用此构造来对满足某些条件的行进行求和
SUM(IF(condition, sum_column_name, 0))
如果要返回包含三个总和的一行
,您的查询可能如下所示SELECT
SUM(IF(t.date = '$today', pageview, 0)) AS pageview_today,
SUM(IF(t.date BETWEEN '$week' AND '$today', pageview, 0)) AS pageview_week,
SUM(IF(DATE_FORMAT(t.date, '%Y-%m') = '$month', pageview, 0)) AS pageview_month
FROM statistics t
WHERE user = '$id' AND (
t.date = '$today'
OR (t.date BETWEEN '$week' AND '$today')
OR DATE_FORMAT(t.date, '%Y-%m') = '$month'
)
或者您可以进行3次查询,并将其与UNION
结合使用,如@quazardous所述。此方法将为您提供3个不同的行。
答案 2 :(得分:0)
使用Union?
Select a from B
Union
Select B from C
...