2015-10-12 59 views
0
SELECT * 
FROM 
( 
    SELECT com_jobcard.job_card_num, 
    sum(worked_qty),employee.emp_name 
    FROM timer_completed 
    INNER JOIN process ON process.id = timer_completed.process_id 
    INNER JOIN com_jobcard ON com_jobcard.id = timer_completed.job_card_id 
    INNER JOIN employee ON employee.id = timer_completed.employee_id 
            AND process.id = '611' 
            AND timer_completed.group_id = '60' 
    AND timer_completed.report_date = DATE_ADD(CURDATE(), INTERVAL -1 DAY) 
    ORDER BY com_jobcard.id DESC 
) AS tmp_table 
GROUP BY com_jobcard.job_card_num 

使用GROUPBY和ORDERBY在這段代碼中我使用Group by選項,但我需要的結果的遞減順序com_jobcard.id如果我使用它返回上面的查詢:在同一查詢

#1054 - 未知' 語句'中的'com_jobcard.job_card_num'列。

請幫幫我。

+1

你想完成什麼?您的查詢不是真正有效的SQL。即使您可以讓MySQL接受它,您的查詢也會使用(錯誤)功能,其中MySQL允許'select'中不在'group by'中的任何列。所以,像'emp_name'這樣的列會得到*不確定的*值。 –

回答

0

使用

GROUP BY tmp_table.job_card_num 
0

兩件事情: 1)在子查詢需要的所有列被命名。這會,如果你使用的是「熱門選擇」子句中的子查詢清除錯誤#1054

sum(worked_qty) as 'WorkedTotal' 

2)令纔可用。您將需要使用Order by by Where group by by,反之亦然

0

您不必要地在此處嵌套查詢。您可以通過將ORDER BY放在GROUP BY之後來訂購聚合查詢結果集。另外,就像Gordon在他的評論中指出的那樣,你濫用非標準的MySql擴展到GROUP BY。除非你瞭解它,否則這會讓你發瘋。 https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html

嘗試重構你的查詢是這樣的:

SELECT com_jobcard.job_card_num, 
     sum(worked_qty), 
     employee.emp_name, 
     com_jobcard.id 
    FROM timer_completed 
    JOIN process ON process.id = timer_completed.process_id 
    JOIN com_jobcard ON com_jobcard.id = timer_completed.job_card_id 
    JOIN employee ON employee.id = timer_completed.employee_id 
       AND process.id = '611' 
       AND timer_completed.group_id = '60' 
       AND timer_completed.report_date = DATE_ADD(CURDATE(), INTERVAL -1 DAY) 
    GROUP BY com_jobcard.job_card_num, employee.emp_name, com_jobcard.id 
    ORDER BY com_jobcard.id DESC 

除了比你提出的查詢簡單,這正確處理GROUP BY並得到您所指定的順序。