2010-09-27 76 views
0

如何使用該查詢正確分組:如何正確放置GROUP BY?

$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; 

我在串聯真的很新。

回答

0

至少在大多數SQL DBMS中(MySQL在此區域中有寬鬆規則),您同樣需要GROUP BY'id'和'A.Model'。您需要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之後)的每一端添加了一個空格,以確保該部分正常。

+0

concat的空間函數是什麼?你有concat的教程網站嗎?我想了解更多。 – klox 2010-09-27 04:04:46

+0

關於這些空格的關鍵點是確保您沒有'A.NIK = B.NIKWHERE B.EmpID = 13GROUP BY id,... B.NameORDER BY DateLIMIT 10' - 其中關鍵字正在運行到之前令牌,導致語法錯誤。我沒有特定的在線參考指向你 - 對不起。 – 2010-09-27 05:44:07