如何正确放置GROUP BY?

时间:2010-09-27 03:41:59

标签: php mysql group-by concatenation

如何在此查询中正确使用分组:

$sQuery = "SELECT id,DATE(A.Inspection_datetime) AS Date,
                              A.Model, COUNT(A.Serial_number) AS Qty,
                              B.name
                      FROM inspection_report AS A
                      LEFT JOIN Employee AS B
                      ON A.NIK=B.NIK
                      GROUP BY Date, B.name".$sWhere.$sOrder.$sLimit;

我是串联的新人。

1 个答案:

答案 0 :(得分:0)

你也需要GROUP BY'id'和'A.Model',至少在大多数SQL DBMS中(MySQL在这方面有较宽松的规则)。您需要GROUP BY来在WHERE子句之后和ORDER BY子句之前。因此:

$sGroupBy = " GROUP BY id, Date, A.Model, B.Name ";
$sQuery = "SELECT id,DATE(A.Inspection_datetime) AS Date,
                          A.Model, COUNT(A.Serial_number) AS Qty,
                          B.name
                  FROM inspection_report AS A
                  LEFT JOIN Employee AS B
                  ON A.NIK=B.NIK " .
                  $sWhere.$sGroupBy.$sOrder.$sLimit;

请注意,您必须确保有空格来分隔您连接在一起的各个子句;我在$sGroupBy的每一端(以及B.NIK之后)添加了一个空格,以确保该部分正常。