我有以下问题:
INSERT INTO StatisticalConsultationAgreement VALUES (
queryType, entityCode, entityType, queryClass,queryTables,period,
COUNT(queryClass), SUM(numberRecords), SUM(recordsFound),
SUM(NorecordsFound), NOW(), 'system');
SELECT
MONTH(EndDateTimeProcessing),YEAR(EndDateTimeProcessing),
entityType,
entityCode,
queryType,
queryClass,
EndDateTimeProcessing as period
FROM agreementFile
WHERE
MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB( CURDATE(), INTERVAL 1 MONTH ))
AND YEAR(EndDateTimeProcessing)=YEAR(CURDATE())
GROUP BY entityType,entitycode,queryType, queryClass;
当我运行查询时,我得到了下一个错误:
Error code 1111, SQL state HY000: Invalid use of group function
Line 1, column 1
Executed successfully in 0,002 s.
Line 5, column 2
为什么选择这个?
如何解决?
答案 0 :(得分:0)
您没有对EndDateTimeProcessing
进行分组,当您尝试执行插入操作时,无法确定应从分组行中选择哪个EndDateTimeProcessing
值。
解决方案是将其添加到组子句中:
GROUP BY entityType,entitycode,queryType, queryClass, EndDateTimeProcessing;
或者您使用函数组作为MAX(),MIN()等
最好的问候
修改
正如Gordon Linoff所说,你也在将查询与INSERT混合,一切都应该通过查询得到。
正确的语法应该是:
INSERT INTO StatisticalConsultationAgreement
SELECT
'queryType', --I don't know what is the query type so i put it on single quote
entityCode,
entityType,
queryClass,
queryTables,
MAX(EndDateTimeProcessing), --Period put on group function MAX, but it cant be grouped below or put into another group function
COUNT(queryClass), --
SUM(numberRecords), -- ASUMING THOSE ARE COLUMNS IN agreementFile
SUM(recordsFound), --
SUM(NorecordsFound),--
NOW(),
'system'
FROM agreementFile
WHERE
MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB( CURDATE(), INTERVAL 1 MONTH ))
AND YEAR(EndDateTimeProcessing)=YEAR(CURDATE())
GROUP BY entityType,entitycode,queryType, queryClass;
查询字段MONTH(EndDateTimeProcessing),YEAR(EndDateTimeProcessing),
已删除,因为我不知道应该在哪里
答案 1 :(得分:0)
您在values
中混合了select
语句和insert
语句。您只需要select
。这是我对你想要的最好的猜测:
INSERT INTO StatisticalConsultationAgreement
SELECT queryType, entityCode, entityType, queryClass,queryTables,period,
COUNT(queryClass), SUM(numberRecords), SUM(recordsFound),
SUM(NorecordsFound), NOW(), 'system'
FROM agreementFile
WHERE MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB( CURDATE(), INTERVAL 1 MONTH )) AND
YEAR(EndDateTimeProcessing)=YEAR(CURDATE())
GROUP BY entityType, entitycode, queryType, queryClass;
但是,您还应在StatisticalConsultationAgreement
声明中列出insert
的列名。