如何在左连接中使用不同的WHERE子句

时间:2011-01-19 01:47:45

标签: mysql join count where-clause group-by

我有两个文本字段,我在WHERE CLAUSE中特意将每个文本字段值发布到MySQL查询中。

$sWhere = " WHERE MONTH(Inspection_datetime) = '".$Month."' AND 
            YEAR(Inspection_datetime) = '".$Year."' ";

然后我尝试将此查询组合成如下所示:

$sQuery = "SELECT A.id,A.Line,
                  week1.1st, week2.2nd, week3.3rd, week4.4th, week5.5th,
                  IFNULL(week1.1st,0) + IFNULL(week2.2nd,0) + IFNULL(week3.3rd,0)
                + IFNULL(week4.4th,0) + IFNULL(week5.5th,0) AS Total
           FROM inspection_report AS A
           LEFT JOIN(
                     SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 +
                                   SUM(C)*0.1)/COUNT(Serial_number) AS 1st
                     FROM inspection_report
                     WHERE DAY(Inspection_datetime) BETWEEN 1 AND 7
                     GROUP BY Line, WEEK(Inspection_datetime),
                                    YEAR(Inspection_datetime)
                     ) AS week1 USING (Line)

                 LEFT JOIN(
                           SELECT Line, (SUM(S) + SUM(A) + SUM(B)*0.4 + SUM(C)*0.1)/COUNT(Serial_number) AS 2nd
                           FROM inspection_report
                           WHERE DAY(Inspection_datetime) BETWEEN 8 AND 14
                           GROUP BY Line, WEEK(Inspection_datetime), YEAR(Inspection_datetime)
                           ) AS week2 USING (Line)";
.........//SAME LIKE ABOVE JUST CHANGE INTO another week's range

$sWhere = " WHERE MONTH(Inspection_datetime) = '".$Month."' AND
           YEAR(Inspection_datetime) = '".$Year."' ";

$sGroupBy = " GROUP BY A.Line ";
$sQuery.= $sWhere.$sGroupBy;

我希望它可以每周统计数据,也可以按$Month$Year进行过滤。

但我的结果不正确。结果计算所有月份和全年的每周数据。 我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:0)

您需要将WHERE MONTH(Inspection_datetime) = '".$Month."' AND YEAR(Inspection_datetime) = '".$Year.添加到每个子查询

您当前的查询存在一些问题:

  1. 您只是通过Line字段加入表格,您告诉MySql要做的事情是找到包含一个月和一年数据的行,并为这些行提取所有每周数据。< / LI>
  2. 您正在多次加入和分组表(每周一次),是否需要这样做?如果你可以按行获得每周结果,那么查询会更快。
  3. 您要为每月7 天创建新的子查询,但希望按
  4. 显示结果