来自Specified Twice Table for 'DELETE' in MariaDB的引用
在我将引用中的查询实现到代码中之后,我在yii2中出错了
查询:
public function actionDeleteduplicate($date){
Yii::$app->db->createCommand("DELETE t1
FROM HrAttLogsFormatted t1
INNER JOIN
(
SELECT FingerId, MIN(CreatedDate) AS MinCreatedDate
FROM HrAttLogsFormatted
WHERE DateIn = '".$date."' AND Late != ''
GROUP BY FingerId
HAVING COUNT(FingerId) > 1
) t2
ON t1.FingerId = t2.FingerId AND t1.CreatedDate = t2.MinCreatedDate
")->queryAll();
$this->redirect(['index']);
}
结果:
SQLSTATE [HY000]:常规错误正在执行的SQL是:DELETE t1 FROM HrAttLogsFormatted t1 INNER JOIN(SELECT FingerId, MIN(CreatedDate)AS MinCreatedDate从HrAttLogsFormatted WHERE DateIn ='2019-05-03'和后期!=''GROUP BY FingerId HAVING COUNT(FingerId)> 1)t2在t1.FingerId = t2.FingerId和 t1.CreatedDate = t2.MinCreatedDate
有人知道代码有什么问题吗?
答案 0 :(得分:2)
该问题可能与您在delete和子查询中具有相同表的事实有关。尝试通过嵌套查询强制数据库引擎使用临时表:
DELETE t1
FROM HrAttLogsFormatted t1
INNER JOIN (
select FingerId, MinCreatedDate
FROM (
SELECT FingerId, MIN(CreatedDate) AS MinCreatedDate
FROM HrAttLogsFormatted
WHERE DateIn = '".$date."' AND Late != ''
GROUP BY FingerId
HAVING COUNT(FingerId) > 1
) t3
) t2 ON t1.FingerId = t2.FingerId AND t1.CreatedDate = t2.MinCreatedDate
顺便说一句:您不应该直接在SQL中使用PHP变量,而应该看看binding params。